java – 将GMT中的XMLGregorianCalendar转换为LocalDateTime太平洋时间
作者:互联网
我正在尝试将以GMT / UTC格式发送的XMLGregorianCalendar转换为America / Los_Angeles时区的Java 8 LocalDateTime而没有运气.
这是我尝试过的,无法将时间转换为太平洋时间.
//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()来执行此操作,这将保留瞬间并修改区域:
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);
}
标签:date-conversion,java,java-8,java-time 来源: https://codeday.me/bug/20190828/1749686.html