问题描述
我正在尝试将以GMT/UTC格式发送的XMLGregorianCalendar转换为America/Los_Angeles时区中的Java 8 LocalDateTime,但运气不好.
I'm trying to convert XMLGregorianCalendar which is sent in GMT/UTC format to Java 8 LocalDateTime in America/Los_Angeles timezone with no luck.
这是我尝试过的方法,无法将时间转换为太平洋时间.
Here is what I tried and couldn't get the time converted to Pacific time.
//xmlDate is 2017-11-13T00:00:00Z
ZonedDateTime zDateTime = xmlDate.toGregorianCalendar().toZonedDateTime().toLocalDateTime().atZone(ZoneId.of("America/Los_Angeles"));
LocalDateTime localDateTime = zDateTime.toLocalDateTime();
//Expected localDateTime is 2017-11-12T16:00. But I only get 2017-11-13T00:00
我想念什么?
推荐答案
atZone()
并没有执行您认为的操作.它仅将时区附加到日期,而没有保留时间点.您必须使用ZonedDateTime#withZoneSameInstant()
进行操作,该命令可以保持即时并修改区域:
atZone()
does not do what you think it does. It merely attaches a timezone to a date without preserving the instant in time. You must do it using ZonedDateTime#withZoneSameInstant()
, which keeps the instant and modifies the zone:
public static void main(String[] args) throws Exception {
XMLGregorianCalendar xc = DatatypeFactory.newInstance().newXMLGregorianCalendar(2017, 10, 13, 0, 0, 0, 0, 0);
System.out.println(xc);
GregorianCalendar gc = xc.toGregorianCalendar();
System.out.println(gc);
ZonedDateTime zdt = gc.toZonedDateTime();
System.out.println(zdt);
LocalDateTime ldt = zdt.withZoneSameInstant(ZoneId.of("America/Los_Angeles")).toLocalDateTime();
System.out.println(ldt);
}
这篇关于将GMT中的XMLGregorianCalendar转换为LocalDateTime太平洋时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!