Convert XMLGregorianCalendar in GMT to LocalDateTime Pacific time

白昼怎懂夜的黑 提交于 2019-12-05 21:04:22

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);
}

Use DateTimeFormatter pattern to clearly define the date and time format, and with defined zoneId.

String xmlDate = "2017-11-13T00:00:00Z";

DateTimeFormatter formatInput =DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZone(ZoneId.of("UTC"));
DateTimeFormatter formatOutput =DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm").withZone(ZoneId.of("America/Los_Angeles"));

ZonedDateTime zoned = ZonedDateTime.parse(xmlDate,formatInput);

System.out.println("Output date and time: "+formatOutput.format(zoned));

Output date and time: 2017-11-12T16:00

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!