【问题标题】:Java 8 LocalDateTime has different resultsJava 8 LocalDateTime 有不同的结果
【发布时间】:2018-10-22 16:53:48
【问题描述】:

我正在尝试更新一些代码以使用 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());

//正确的日期是我想要的 2018 年 9 月 5 日星期三 20:28:59 GMT-11:00

【问题讨论】:

  • 错误的课程,LocalDateTime 不能代表片刻,正如其课程文档所解释的那样。
  • 使用 Java 8,您无需自己构建格式化程序。它内置为DateTimeFormatter.ISO_OFFSET_DATE_TIME。此外,OffsetDateTime 是一个比ZonedDateTime 更好的类,因为你所拥有的和你想要的是像 +04:00 或 GMT 这样的偏移量,而不是像澳大利亚/布里斯班或美国/纽约这样的区域。
  • 无缘无故投反对票?!!嘘

标签: date datetime java-8


【解决方案1】:

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

LocalDateTimeDocumentation 清楚地解释了这一点:

此类不存储或表示时区。相反,它是对日期的描述,用于生日,结合挂钟上的当地时间。如果没有偏移或时区等附加信息,它就不能代表时间线上的瞬间。

您应该考虑使用OffsetDateTimeZonedDateTime

【讨论】:

  • 嗨,是的...我能够通过使用 ZonedDateTime 解决这个问题。谢谢。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-19
    • 2020-07-21
    • 2015-12-19
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 2018-02-12
    相关资源
    最近更新 更多