简体   繁体   English

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

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

I want to format a UTC date-time in a specific ISO 8601 format like 2020-02-28T14:10:23+00:00 but not 2020-02-28T14:10:23Z .我想以特定的 ISO 8601 格式格式化 UTC 日期时间,例如2020-02-28T14:10:23+00:00但不是2020-02-28T14:10:23Z I don't want Z at the end but +00:00.我不想要 Z 最后而是 +00:00。 I tried all the formats in simpleDateFormat doc and no format seems to give the above-mentioned one.我尝试了simpleDateFormat doc 中的所有格式, 似乎没有提供上述格式的格式。

I know both represents same time irrespective of the format but it needs to be formatted like that for backward compatibility reasons.我知道无论格式如何,两者都表示相同的时间,但出于向后兼容性的原因,它需要像那样格式化。

Here is the java code that I tried,这是我尝试过的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()));

It could be achieved by replacing z with +00:00 in the formatted string but it doesn't seems to be a good option.可以通过在格式化字符串中用 +00:00 替换 z 来实现,但这似乎不是一个好的选择。

According documentation of DateTimeFormatter根据DateTimeFormatter 文档

Offset X and x : This formats the offset based on the number of pattern letters.偏移量 X 和 x :这根据模式字母的数量格式化偏移量。 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'.一个字母只输出小时,例如“+01”,除非分钟不为零,在这种情况下也会输出分钟,例如“+0130”。 Two letters outputs the hour and minute, without a colon, such as '+0130'.两个字母输出小时和分钟,没有冒号,例如“+0130”。 Three letters outputs the hour and minute, with a colon, such as '+01:30' .三个字母输出小时和分钟,带一个冒号,例如 '+01:30' Four letters outputs the hour and minute and optional second, without a colon, such as '+013015'.四个字母输出小时和分钟以及可选的秒,没有冒号,例如“+013015”。 Five letters outputs the hour and minute and optional second, with a colon, such as '+01:30:15'.五个字母输出小时和分钟以及可选的秒,带有冒号,例如“+01:30:15”。 Six or more letters throws IllegalArgumentException.六个或更多字母抛出 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' .当要输出的偏移量为零时,模式字母“X”(大写)将输出“Z”,而模式字母“x”(小写)将输出“+00”、“+0000”或“+00” :00'

Try with xxx like in:尝试使用xxx例如:

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

which returns something like返回类似的东西

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

Based on Java version 13, tested with jshell OpenJDK 13;基于 Java 版本 13,使用jshell OpenJDK 13 测试; DateTimeFormatter is available in Java 8 or later DateTimeFormatter在 Java 8 或更高版本中可用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM