【问题标题】:Java DateTimeFormatter parse YearMonth with offsetJava DateTimeFormatter 使用偏移量解析 YearMonth
【发布时间】: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);

这种特定格式的正确模式是什么?

是否有可能创建一个解析这个StringDateTimeFormatter,或者我应该操作字符串"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


【解决方案1】:

偏移量+03:00 的正确模式是XXX(有关详细信息,请查看javadoc - 实际上在DateTimeFormatterBuilder 文档中有一个more detailed explanation):

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMXXX");
String str = "2014-08+03:00";
YearMonth yearMonth = YearMonth.parse(str, formatter);
System.out.println(yearMonth);

输出将是:

2014-08

【讨论】:

  • 就是这个!现在我看到“三个字母输出小时和分钟,带有冒号,例如'+01:30'。”谢谢!
猜你喜欢
  • 2019-08-31
  • 2021-12-05
  • 2018-08-06
  • 2022-11-12
  • 2021-11-05
  • 2016-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多