Java 8 LocalDateTime has different results

一个人想着一个人 提交于 2020-01-21 10:33:03

问题


I am trying to update some code to use Java 8's feature for parsing multiple date formats. my local time on my box is set to UTC-11.

the below code works when using the SimpleDateformat.

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
Date correctDate = dateFormat.parse("2018-09-6T03:28:59.039-04:00");

//Gives me correct date  
System.println( correctDate);//Wed Sep 5th 20:28:59 GMT-11:00 2018

I am trying to update this code to give the same date as above with the DateTimeFormatter in Java 8 , so i can handle another date format..

DateTimeFormattter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[.SSS]XXX");
LocalDateTime updateDate = LocalDateTime.parse( "2018-09-6T03:28:59.039-04:00", dtf);

//shows the wrong date of 2018-09-06 03:28:59.039.
System.out.println( updateDate.toString() );// 2018-09-06 03:28:59.039

[solved] I was able to fix this by using ZonedDateTime.

ZonedDateTime zdt = ZonedDateTime.parse("2018-09-6T03:28:59.039-04:00");
zonedDateTime = zdt.withZoneSameInstance(ZoneId.of("GMT"));

Date correctDate = Date.from( zonedDateTime.toInstance());

//correctDate is what i wanted Wed Sep 5th 20:28:59 GMT-11:00 2018


回答1:


As soon as you parse your date string into a LocalDateTime the zone offset is lost because LocalDateTime does not hold any time zone or offset information. When you format the LocalDateTime to a string again, you'll only have the time as it was parsed without offset.

The Documentation of LocalDateTime clearly explains this:

This class does not store or represent a time-zone. Instead, it is a description of the date, as used for birthdays, combined with the local time as seen on a wall clock. It cannot represent an instant on the time-line without additional information such as an offset or time-zone.

You should consider using OffsetDateTime or ZonedDateTime.




回答2:


Solved, using OffsetDateTime as suggested in the accepted 'Answer':

OffsetDateTime odt = OffsetDateTime.parse("2018-09-6T03:28:59.039-04:00");
Date correctDate = Date.from( odt.toInstant());



来源:https://stackoverflow.com/questions/52934212/java-8-localdatetime-has-different-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!