【发布时间】:2017-12-31 00:18:15
【问题描述】:
我在解析表示年份和月份的特殊字符串时遇到问题,其偏移量如下:2014-08+03:00。
所需的输出是YearMonth。
我已经测试过使用各种模式创建自定义 DateTimeFormatter,但它失败了并且抛出了 DateTimeParseException。
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMZ");
TemporalAccessor temporalAccessor = YearMonth.parse(month, formatter);
YearMonth yearMonth = YearMonth.from(temporalAccessor);
这种特定格式的正确模式是什么?
是否有可能创建一个解析这个String 的DateTimeFormatter,或者我应该操作字符串"2014-08+03:00" 并手动将偏移量删除到"2014-08",然后将其解析为YearMonth(或到其他java.time 类)?
编辑:
我进一步调查了 API 及其 .xsd 模式文件,其中属性列为 <xs:attribute name="month" type="xs:gYearMonth"/>,命名空间为 xmlns:xs="http://www.w3.org/2001/XMLSchema">
显然属性的类型是DataTypeConstans.GYEARMONTH,其中“2014-08+03:00”是有效格式。
This 答案解释了如何将String 转换为XMLGregorianCalendar,从那里可以通过OffsetDateTime 转换为YearMonth。
XMLGregorianCalendar result = DatatypeFactory.newInstance().newXMLGregorianCalendar("2014-08+03:00");
YearMonth yearMonth = YearMonth.from(result.toGregorianCalendar().toZonedDateTime().toOffsetDateTime());
但是我仍然很好奇是否可以仅使用自定义 java.time.DateTimeFormatter 将字符串 "2014-08+03:00" 直接解析为 YearMonth。
【问题讨论】:
-
A
YearMonth不包含时区信息... -
是的,我知道,我想知道为什么 API 会在其中包含偏移量,而我自己不需要偏移量。 @assylias
标签: java parsing datetime timezone-offset date-parsing