datejava-8datetime-formatlocaldatedatetimeformatter

Java8 DateFormatter for pattern "Dec 01, 2019 1:00:00 PM +00:00"


I am trying to format the String date, time and zone information.

LocalDateTime.parse("Dec 01, 2019 1:00:00 PM +00:00", DateTimeFormatter.ofPattern("MMM dd, YYYY hh:mm:ss a XXX"));
ZonedDateTime.parse("Dec 01, 2019 1:00:00 PM +00:00", DateTimeFormatter.ofPattern("MMM dd, YYYY hh:mm:ss a XXX"));

Please note for project support reasons i cannot use above java 8.

I am unable to get this parse work, I did try a lot of versions before i posted here. any support is appreciated.

Exception:

Exception in thread "main" java.time.format.DateTimeParseException: Text 'Dec 01, 2019 1:00:00 PM +00:00' could not be parsed at index 13
    at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2052)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1954)
    at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:494)
    at com.parse.Test.main(Test.java:10)

Solution

  • Your date-time string, "Dec 01, 2019 1:00:00 PM +00:00" has timezone offset of 00:00 hours. The java.time API provides us with OffsetDateTime to parse this type of date-time string to.

    Demo:

    import java.time.OffsetDateTime;
    import java.time.format.DateTimeFormatter;
    import java.util.Locale;
    
    class Main {
        public static void main(String[] args) {
            DateTimeFormatter parser = DateTimeFormatter.ofPattern("MMM dd, uuuu h:mm:ss a XXX", Locale.ENGLISH);
            OffsetDateTime odt = OffsetDateTime.parse("Dec 01, 2019 1:00:00 PM +00:00", parser);
            System.out.println(odt);
        }
    }
    

    Output:

    2019-12-01T13:00Z
    

    ONLINE DEMO

    Learn more about the modern Date-Time API from Trail: Date Time.

    What went wrong with your code?

    1. You have used hh whereas your string has only one digit in the hour.
    2. You have used Y instead of y. Note that Y is used for week-based-year. The right symbol for the intended purpose is y or u. Here, you can use y instead of u but I prefer u to y.

    I also recommend you understand the importance of using a Locale while using date-time parsing/formatting API. Check Never use SimpleDateFormat or DateTimeFormatter without a Locale to learn more about it.