gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:49:20 25 4
gpt4 key购买 nike

我必须为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com