0

I have time string in two formats.

2019-03-01T22:22:50.591-08:00   
2019-03-01T22:22:50.591Z

I am using following Java snippet to parse

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:SS" +
              ".SSS'Z'", Locale.US);
Date date = df.parse(dateString);

Its working on second string but failing on first. What common code can be there to parse both of them?

Shashwat Kumar
  • 5,159
  • 2
  • 30
  • 66
  • [`ZonedDateTime.parse()`](https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html#parse-java.lang.CharSequence-). But I'll let Basil go into the detail. – shmosel Mar 28 '19 at 01:21
  • This function needs a DateTimeFormatter for string pattern. I am not able to find correct pattern. – Shashwat Kumar Mar 28 '19 at 01:50
  • 2
    No, it doesn't. – shmosel Mar 28 '19 at 01:51
  • 1
    Stay away from `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `Instant` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). You don’t need an explicit formatter: `OffsetDateTime.parse(dateString)` works for both example strings. – Ole V.V. Mar 28 '19 at 04:18
  • 1
    Both `-08:00` and `Z` are UTC offsets. `Z` means UTC (offset zero or “Zulu”). So both strings are really in the same format. It’s the international standard ISO 8601 format. – Ole V.V. Mar 28 '19 at 04:26
  • 1
    @shmosel No, not `ZonedDateTime`, You can get by with that, but it is misleading as there is only an offset-from-UTC (hours-minutes-seconds) in the inputs, not a time zone (`Continent/Region`). Better would be `OffsetDateTime.parse( "2019-03-01T22:22:50.591-08:00" )`. – Basil Bourque Mar 28 '19 at 06:25
  • @BasilBourque I was waiting for that. It does work though. – shmosel Mar 28 '19 at 06:26

1 Answers1

0

This might be what you're looking for: "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"

Date parsed1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.US).parse("2019-03-01T22:22:50.591Z");
System.out.println(parsed1); // Fri Mar 01 16:22:50 CST 2019

Date parsed2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.US).parse("2019-03-01T22:22:50.591-08:00");
System.out.println(parsed2); // Sat Mar 02 00:22:50 CST 2019

As Basil points out below, these also work if you are running Java 8+ or a backport of JSR 310:

    OffsetDateTime parsed1 = OffsetDateTime.parse("2019-03-01T22:22:50.591Z");
    System.out.println(parsed1); // Fri Mar 01 16:22:50 CST 2019

    OffsetDateTime parsed2 = OffsetDateTime.parse("2019-03-01T22:22:50.591-08:00");
    System.out.println(parsed2); // Sat Mar 02 00:22:50 CST 2019
Not a JD
  • 1,864
  • 6
  • 14
  • Yup, agree, but did not want to turn too many screws at the same time. I have two clients that still run JBoss EAP 4.2 in production and won't use a JSR 310 backport... Have edited. – Not a JD Mar 28 '19 at 13:24