ISO 8601日期时间格式,包含“ Z”和偏移量“ +0000”

ISO 8601 date-time format combining 'Z' and offset of '+0000'

我正在使用ISO 8601中的日期时间格式。我有以下模式:

"yyyy-MM-dd'T'HH:mm:ssZZ'Z'"

输出为:

"2015-11-17T00:00:00+0000Z"

我的问题是输出是否正常,如果考虑到日期+0000和Z都可能具有相同的含义,则表示时区偏移量/ id。 在此先感谢您的澄清=)


不行不行

不,Z是自UTC的偏移量,因此不应将其与+00:00+0000的数值偏移量冗余地组合。

ISO 8601

虽然我无法使用ISO 8601规范的付费副本,但Wikipedia页上明确指出Z必须遵循时间:

…add a Z directly after the time without a space.

IETF RFC 3339

免费提供的RFC 3339(ISO 8601的配置文件)将Z定义为附于一天中的时间:

A suffix … applied to a time …

RFC还用正式的ABNF表示法指出我们应该使用Z或数字。在ABNF中,斜杠(SOLIDUS)表示"或"(不包括"或"),而方括号对则表示"可选"。

time-numoffset = ("+" /"-") time-hour [[":"] time-minute]

time-zone ="Z" / time-numoffset

此外,规范的5.4节特别建议不要包含冗余信息。

爪哇

解析/生成字符串时,默认情况下,内置于Java中的现代java.time类使用标准ISO 8601格式。请参见Oracle教程。

解析文本输入

使用Z

1
Instant instant = Instant.parse("2019-01-23T12:34:56.123456789Z" ) ;

使用+00:00

1
OffsetDateTime odt = OffsetDateTime.parse("2019-01-23T12:34:56.123456789+00:00" ) ;

产生文字输出

要使用Z创建字符串,只需调用Instant::toString

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

要使用00:00创建字符串,请调用OffsetDateTime::format。使用具有定义格式格式的DateTimeFormatter生成文本。

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上实时运行的代码。