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
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:
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]
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