ISO 8601 date-time format combining 'Z' and offset of '+0000'
我正在使用ISO 8601中的日期时间格式。我有以下模式:
输出为:
我的问题是输出是否正常,如果考虑到日期+0000和Z都可能具有相同的含义,则表示时区偏移量/ id。 在此先感谢您的澄清=)
不行不行
不,
ISO 8601
虽然我无法使用ISO 8601规范的付费副本,但Wikipedia页上明确指出
…add a Z directly after the time without a space.
IETF RFC 3339
免费提供的RFC 3339(ISO 8601的配置文件)将
A suffix … applied to a time …
RFC还用正式的ABNF表示法指出我们应该使用
time-numoffset = ("+" /"-") time-hour [[":"] time-minute]
time-zone ="Z" / time-numoffset
此外,规范的5.4节特别建议不要包含冗余信息。
爪哇
解析/生成字符串时,默认情况下,内置于Java中的现代java.time类使用标准ISO 8601格式。请参见Oracle教程。
解析文本输入
使用
1 | Instant instant = Instant.parse("2019-01-23T12:34:56.123456789Z" ) ; |
使用
1 | OffsetDateTime odt = OffsetDateTime.parse("2019-01-23T12:34:56.123456789+00:00" ) ; |
产生文字输出
要使用
1 | String output = Instant.now().toString() ; // Capture the current moment in UTC, then generate text representing that value in standard ISO 8601 using the `Z` offset-indicator. |
2019-05-22T21:00:52.214709Z
要使用
1 2 | DateTimeFormatter f = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSxxx" ) ; String output = OffsetDateTime.now( ZoneOffset.UTC ).format( f ) ; |
2019-05-22T21:00:52.319076+00:00
截断
您可能想要截断任何微秒或纳秒。
1 2 3 4 | Instant .now() .truncatedTo( ChronoUnit.MILLIS ) .toString() |
2019-05-22T21:11:28.970Z
…和…
1 2 3 4 5 6 | OffsetDateTime .now( ZoneOffset.UTC ) .truncatedTo( ChronoUnit.MILLIS ) .format( DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSxxx" ) ) |
2019-05-22T21:11:29.078+00:00
请参阅在IdeOne.com上实时运行的代码。