Java8- ZonedDateTime with DateTimeFormatter not recognizing the format

Venkat picture Venkat · Jan 26, 2016 · Viewed 15.6k times · Source

I am using the ZonedDateTime with DateTimeFormatter of Java 8. When I try to parse my own pattern it doesn't recognizes and throws an exception.

    String oraceDt = "1970-01-01 00:00:00.0";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");
    ZonedDateTime dt = ZonedDateTime.parse(oraceDt, formatter);

Exception in thread "main" java.time.format.DateTimeParseException: Text '1970-01-01 00:00:00.0' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 1970-01-01T00:00 of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1918)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1853)
at java.time.ZonedDateTime.parse(ZonedDateTime.java:597)
at com.timezone.Java8DsteTimes.testZonedDateTime(Java8DsteTimes.java:31)
at com.timezone.Java8DsteTimes.main(Java8DsteTimes.java:11)

Caused by: java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 1970-01-01T00:00 of type java.time.format.Parsed

Answer

Meno Hochschild picture Meno Hochschild · Jan 26, 2016

Well, you want to create a ZonedDateTime which always refers to a timezone but your input does not contain such an information, and you have also not instructed your formatter to use a default timezone if the input is missing a zone. There are two solutions for your problem:

  1. Instruct your parser to use a timezone (here using the system tz as example):

    String oraceDt = "1970-01-01 00:00:00.0";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");
    ZonedDateTime zdt = 
      ZonedDateTime.parse(oraceDt, formatter.withZone(ZoneId.systemDefault()));
    System.out.println(zdt); // in my default zone => 1970-01-01T00:00+01:00[Europe/Berlin]
    
  2. Use another result type which does not need a timezone (here LocalDateTime):

    String oraceDt = "1970-01-01 00:00:00.0";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");
    LocalDateTime ldt = LocalDateTime.parse(oraceDt, formatter);
    System.out.println(ldt); // 1970-01-01T00:00