Java 8 LocalDateTime有不同的结果 [英] Java 8 LocalDateTime has different results

查看:320
本文介绍了Java 8 LocalDateTime有不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更新一些代码以使用Java 8的功能来解析多种日期格式.我在盒子上的本地时间设置为 UTC-11 .

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.

下面的代码在使用SimpleDateformat时起作用.

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

我正在尝试使用Java 8中的DateTimeFormatter更新此代码以提供与上述相同的日期,以便我可以处理其他日期格式..

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

[已解决] 我可以通过使用ZonedDateTime来解决此问题.

[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是我想要的2018年9月5日星期三20:28:59 GMT-11:00

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

推荐答案

将日期字符串解析为LocalDateTime后,区域偏移就会丢失,因为LocalDateTime不包含任何时区或偏移信息. 再次将LocalDateTime格式化为字符串时,解析后的时间将没有偏移.

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.

您应该考虑使用OffsetDateTimeZonedDateTime.

这篇关于Java 8 LocalDateTime有不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆