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):
Use another result type which does not need a timezone (here
LocalDateTime
):Here is an small example of using the ZonedDateTime with DateTimeFormatter of Java 8.
The ZonedDateTime class permits you to create a date/time object with a time zone. The default time zone will be used; i.e., the time zone you have established on your computer. You can use the DateTimeFormatter class to display the time zone. In the Java code, the time zone is displayed as zone offset, zone name and zone ID. Note that the date time formatter pattern is "Z", "z", and "VV", respectively. The program also creates a date/time object and then adds the zone ID using the of method of the ZoneId class. Finally, a time zone is added to another date/time object using the of method of the ZoneOffset class.