将LocalDateTime格式化为具有偏移量的XMLGregorianCalender

问题描述 投票:0回答:1

我有一个LocalDateTime的实例。

我需要将其映射为XMLGregorianCalendar(在这里使用JAXB),最后是XML,我希望有时间在XML文档中看起来像下面这样:2020-03-04T19:45:00.000 + 1:00(1小时是UTC的偏移量)。

我尝试使用DateTimeFormatter将LocalDateTime转换为字符串,然后将其映射到XMLGregorianCalender。

我现在有两个问题:

  1. 我无法在DateTimeFormatter中找到任何格式化程序哪种格式与UTC偏移时间?做这样的事情存在,或者我需要定义格式化程序模式?

    第二,如果我能够将String格式的LocalDateTime格式化,需要,如果我仅从创建XMLGregorianCalendar就足够了字符串表示形式?

java xml datetime-format xmlgregoriancalendar
1个回答
0
投票
如果时区偏移量是从JVM的默认时区派生的,则按如下所示进行编码:

LocalDateTime localDateTime = LocalDateTime.now(); ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault()); // <== default OffsetDateTime offsetDateTime = zonedDateTime.toOffsetDateTime(); XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance() .newXMLGregorianCalendar(offsetDateTime.toString()); System.out.println(localDateTime); // 2020-03-04T15:58:09.604171800 System.out.println(zonedDateTime); // 2020-03-04T15:58:09.604171800-05:00[America/New_York] System.out.println(offsetDateTime); // 2020-03-04T15:58:09.604171800-05:00 System.out.println(xmlGregorianCalendar); // 2020-03-04T15:58:09.604171800-05:00

如果要对+01:00的偏移量进行硬编码,请按照以下步骤进行:

LocalDateTime localDateTime = LocalDateTime.now(); OffsetDateTime offsetDateTime = localDateTime.atOffset(ZoneOffset.ofHours(1)); // <== hardcoded XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance() .newXMLGregorianCalendar(offsetDateTime.toString()); System.out.println(localDateTime); // 2020-03-04T16:00:04.437550500 System.out.println(offsetDateTime); // 2020-03-04T16:00:04.437550500+01:00 System.out.println(xmlGregorianCalendar); // 2020-03-04T16:00:04.437550500+01:00

或类似这样:

LocalDateTime localDateTime = LocalDateTime.now(); XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance() .newXMLGregorianCalendar(localDateTime.toString()); xmlGregorianCalendar.setTimezone(60); // <== hardcoded System.out.println(localDateTime); // 2020-03-04T16:03:09.032191 System.out.println(xmlGregorianCalendar); // 2020-03-04T16:03:09.032191+01:00

© www.soinside.com 2019 - 2024. All rights reserved.