Java 8 LocalDateTime具有不同的结果

时间:2018-10-22 16:53:48

标签: date datetime java-8

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

下面的代码在使用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更新此代码以提供与上述相同的日期,以便我可以处理其他日期格式。.

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来解决此问题。

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

2 个答案:

答案 0 :(得分:4)

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

LocalDateTime的{​​{3}}清楚地解释了这一点:

  

此类不存储也不表示时区。相反,它是对用于生日的日期的描述,以及在墙上时钟上看到的本地时间。如果没有其他信息(例如偏移量或时区),则无法在时间轴上表示时刻。

您应该考虑使用OffsetDateTimeZonedDateTime

答案 1 :(得分:1)

已解决,使用接受的“答案”中建议的OffsetDateTime:

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