Search code examples
javazoneddatetime

Error: "Unable to obtain ZonedDateTime from TemporalAccessor" for format "yyyy-MM-dd hh:mm:ss z"


I have an input stream of data that contains Date in the format "yyyy-MM-dd hh:mm:ss z", wherein the TimeZone needs to be preserved while propagating the Date further. Below is the test program (with error stack) - what is wrong in my solution ?

public class Test {

public static void main(String[] args) {
    try {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss z");
        ZonedDateTime zdt = ZonedDateTime.parse("2016-12-09 09:30:21 UTC", dtf);
        System.out.println(zdt);
    } catch (Exception e) {
        System.err.println("Exception in 1st approach: " + e.getMessage());
    }

    try {
        DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd hh:mm:ss z").toFormatter();
        ZonedDateTime zdt = ZonedDateTime.parse("2016-12-09 09:30:21 UTC", dtf);
        System.out.println(zdt);
    } catch (Exception e) {
        System.err.println("Exception in 2nd approach: " + e.getMessage());
    }
  }
}

Output (exception msg):

Exception in 1st approach: Text '2016-12-09 09:30:21 UTC' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {HourOfAmPm=9, MinuteOfHour=30, MicroOfSecond=0, SecondOfMinute=21, NanoOfSecond=0, MilliOfSecond=0},ISO,UTC resolved to 2016-12-09 of type java.time.format.Parsed

Exception in 2nd approach: Text '2016-12-09 09:30:21 UTC' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {HourOfAmPm=9, MinuteOfHour=30, MicroOfSecond=0, SecondOfMinute=21, NanoOfSecond=0, MilliOfSecond=0},ISO,UTC resolved to 2016-12-09 of type java.time.format.Parsed

JDK version 1.8.0_111

I have read the similar questions in zoneddatetime tag but could not find a solution to the issue.


Solution

  • you should use DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z"); instead of using

      DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss z");
    

    So h in your pattern must be H. according to documentation h is used when you define clock-hour-of-am-pm so in addition you should have a as am-pm-of-day in your patern as well or just use H