如何在 Java 中将 UTC 日期时间转换为 ISO 8601 格式?

how to convert UTC date-time into ISO 8601 format in Java?

我想将 UTC 日期时间格式化为特定的 ISO 8601 格式,例如 2020-02-28T14:10:23+00:00 但不是 2020-02-28T14:10:23Z。我最后不想要 Z,而是 +00:00。我尝试了 simpleDateFormat doc 中的所有格式,但似乎没有格式提供上述格式。

我知道无论格式如何,两者都代表相同的时间,但出于向后兼容的原因,它需要像那样格式化。

这是我试过的 java 代码,

final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.format(new Date()));

可以通过在格式化字符串中将 z 替换为 +00:00 来实现,但这似乎不是一个好的选择。

根据DateTimeFormatterdocumentation

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'. Four letters outputs the hour and minute and optional second, without a colon, such as '+013015'. Five letters outputs the hour and minute and optional second, with a colon, such as '+01:30:15'. Six or more letters throws IllegalArgumentException. 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'.

尝试使用 xxx,例如:

DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssxxx").format(ZonedDateTime.now())

其中 returns 类似

2020-02-28T12:42:30+00:00

基于 Java 版本 13,使用 jshell OpenJDK 13 测试; DateTimeFormatter 在 Java 8 或更高版本

中可用