0

I have the following code:

try {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd yyyy HH:mm:ss 'GMT'xxx");
    logger.debug("formatter: " + formatter);
    ZonedDateTime zdt = ZonedDateTime.parse(rtime, formatter);
} catch (DateTimeParseException e) {
    if (logger.isDebugEnabled()) {
        logger.debug("Failed to parse device time [" + rtime + "] ", e);
    }
}

rtime here is Jan 17 2019 03:38:06 GMT+00:00

Debug is printing out

formatter: Text(MonthOfYear,SHORT)' 'Value(DayOfMonth,2)' 'Value(YearOfEra,4,19,EXCEEDS_PAD)' 'Value(HourOfDay,2)':'Value(MinuteOfHour,2)':'Value(SecondOfMinute,2)' ''GMT'Offset(+HH:MM,'+00:00')`

The error is :

Failed to parse device time [Jan 17 2019 03:38:06 GMT+00:00] 
java.text.ParseException: Unparseable date: "Jan 17 2019 03:38:06 GMT+00:00"

I tried a few patterns and it is always failing.
Could someone help?

deHaar
  • 17,687
  • 10
  • 38
  • 51
Steve
  • 81
  • 1
  • 7
  • the format is not dependent on 'what time it is'. It depends on what you need to get. what type is rtime? – Stultuske Apr 28 '23 at 06:32
  • rtime is a String. I have a method that takes epoch time as argument my goal is to get the epoch time using zdt.toInstant().toEpochMilli() – Steve Apr 28 '23 at 06:35
  • I copied and ran your code, it works fine here. as @user16320675 suggests, check your locale. – Stultuske Apr 28 '23 at 06:54
  • It is working fine now after adding `Locale.ROOT`. Thanks guys for the help. – Steve Apr 28 '23 at 07:05
  • This can’t be right. You are catching `DateTimeParseException`, but your output reports a `java.text.ParseException`. That output cannot come from that code. – Ole V.V. Apr 28 '23 at 07:47

1 Answers1

1

There are two major problems in your DateTimeFormatter:

  • the missing Locale, which may cause the Locale.getDefault() to be used and that one may not know the abbreviation (e.g. a Locale.ITALIAN would expect gen instead of Jan)
  • the wrong pattern letter for the time zone (the String contains an outdated offset notation, hours from GMT)

You can parse it like this:

public static void main(String[] args) {
    String rtime = "Jan 17 2019 03:38:06 GMT+00:00";
    try {
        DateTimeFormatter formatter = 
                DateTimeFormatter.ofPattern("MMM dd uuuu HH:mm:ss VV", Locale.ENGLISH);
        System.out.println("formatter: " + formatter);
        ZonedDateTime zdt = ZonedDateTime.parse(rtime, formatter);
        System.out.println(zdt);
    } catch (DateTimeParseException e) {
        System.err.println("Failed to parse device time [" + rtime + "] ");
    }
}

Output:

2019-01-17T03:38:06Z[GMT]

You can use a different DateTimeFormatter in order to create different output.


In case you have influence on the input Strings, you may be best adviced removing the GMT from it and only use +00:00, which can be used to create an OffsetDateTime.

deHaar
  • 17,687
  • 10
  • 38
  • 51