0

How to parse this date string in java

"2020-06-12T00:00:00.000+00:00"

I tried the following code :

public static String convertToStandardDateString(String date) {
        // 2020-06-12T00:00:00.000+00:00
        String resDate = null;
        try {
            DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'+'X");
            Date parsedDate = sdf.parse(date);
            resDate = sdf.format(parsedDate);
        } catch (Exception e) {

        }
        return resDate;
    }

I am getting the ParsingException with the above code.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Ram Kowsu
  • 711
  • 2
  • 10
  • 30
  • 3
    Ditch the quoted `+`. – Sotirios Delimanolis Jun 13 '20 at 17:19
  • 1
    I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `OffsetDateTime` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jun 13 '20 at 17:30
  • 1
    Your formatting pattern `"yyyy-MM-dd'T'HH:mm:ss.SSS'+'X"` has quotes around the `+` which means "expect but ignore this text". You should *not* ignore that character, as it is a crucial part of the offset-from-UTC, with `+` meaning hours-minutes-seconds ahead of UTC and `-` meaning behind. Furthermore, no need to define a custom formatting pattern. The `java.time.OffsetDateTime` class can parse that string by default, as seen in [Answer by Deadpool](https://stackoverflow.com/a/62363299/642706). – Basil Bourque Jun 13 '20 at 21:02

1 Answers1

5

Stop using the deprecated java.util.Date and start using the java-8 date-time api. The date string you have represents date time with offset, so you can parse it directly into OffsetDateTime

A date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as 2007-12-03T10:15:30+01:00.

OffsetDateTime offsetDateTime = OffsetDateTime.parse("2020-06-12T00:00:00.000+00:00");
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98