【发布时间】: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 这样的偏移量,而不是像澳大利亚/布里斯班或美国/纽约这样的区域。 -
无缘无故投反对票?!!嘘