Java 8 日期时间格式日期+偏移量

标签 java date datetime formatting java-time

我必须为 Web 服务构造一个 XMLGregorianCalendar,它需要格式为 yyyy-MM-dd+01:00 的日期,其中 之后的值+ 源自时区偏移量。

到目前为止,我已经尝试过:

DateTimeFormatter formatterDateWithOffset = DateTimeFormatter.ofPattern("yyyy-MM-ddZZ");

XMLGregorianCalendar xcal = DatatypeFactory.newInstance()
    .newXMLGregorianCalendar(zonedDateTime.format(formatterDateWithOffset));

但这会导致 IllegalArgumentExcpetion,因为格式化程序会生成 2017-09-29+0200

是否可以为所需格式定义格式字符串?

最佳答案

如果您查看关于 DateTimeFormatter 的 JavaDoc,您会看到:

Offset X and x: This formats the offset based on the number of pattern letters. One letter outputs just the hour, such as '+01', unless the minute is non-zero in which case the minute is also output, such as '+0130'. Two letters outputs the hour and minute, without a colon, such as '+0130'. Three letters outputs the hour and minute, with a colon, such as '+01:30'. ... Pattern letter 'X' (upper case) will output 'Z' when the offset to be output would be zero, whereas pattern letter 'x' (lower case) will output '+00', '+0000', or '+00:00'.

因此 DateTimeFormatter formatterDateWithOffset = DateTimeFormatter.ofPattern("yyyy-MM-ddxxx"); 应该可以工作。

在我的评论中,我建议使用 ZZZZ,因为 JavaDoc 也暗示了这一点,但它也会添加 GMT 部分(ZZZZZ 似乎即使 JavaDoc 声明:“五个字母输出小时、分钟,如果非零则带有可选的,带有冒号”。

关于Java 8 日期时间格式日期+偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46487804/

相关文章:

java - 包含带有 Android 应用程序的文本文档

java - 将 java.lang.reflect.Type 转换为 Class<T>

java - Java/MySQL 中没有时间或时区组件的日期

python - Pandas:将季度数据转换为月度数据

java - 如何在 Jmeter 中使用现有的 Java API 测试

java - 为什么这个线程在 Spring 中继续运行?

javascript - JavaScript 中的时间戳不一致?

iphone - iPhone 设置为 12 小时制时的 NSDateFormatter

python - 绘制分组日期时间 - Pandas

c# - 设置日期和月份格式,但不是他们的顺序