我有几个代码片段。其中有些有效,有些无效,但我不明白为什么。
DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); //(7 positions after last dor)
TIME_FORMATTER.parse("2021-06-22T18:27:03.5577Z")//Broken 4
TIME_FORMATTER.parse("2021-06-22T18:27:03.55770Z")//Broken 5
TIME_FORMATTER.parse("2021-06-22T18:27:03.557700Z")//Working 6
TIME_FORMATTER.parse("2021-06-22T18:27:03.5577000Z")//Working 7
TIME_FORMATTER.parse("2021-06-22T18:27:03.55770000Z")//Broken 8
当 running live at IdeOne.com 时,查看此代码是否有效.
为什么它适用于:decimal separator 之后的 6 位和 7 位数字, 但不是 4、5 或 8 位数字?
如何创建适用于 4、5、6、7 或 8 位数字的格式化程序?
最佳答案
tl;dr
你问:
How to create Format which will work for 4,5,6,7 numbers after point ?
使用预定义的格式化程序,DateTimeFormatter.ISO_INSTANT
.
DateTimeFormatter.ISO_INSTANT.parse("2021-06-22T18:27:03.5577Z")
从不忽略 Z
切勿在格式化模式中将 Z 括起来。那封信承载着重要的信息,而不是单纯的装饰。 该字母表示与 UTC 的零小时-分钟-秒的偏移。您在 Z
周围的单引号表示该字母应该被预期然后被忽略。
忽略偏移量时,您只剩下日期和时间。日期和时间不足以代表一个时刻。我们无法知道您输入的是东京的下午 6:30、图卢兹的下午 6:30 还是托莱多的下午 6:30——所有这些时间都相隔几个小时,非常不同。
对于时间轴上的一个点,我们需要第三部分,偏移量或时区的上下文。
java.time.Instant.parse
您的输入文本符合 java.time 默认使用的 ISO 8601 标准。因此无需指定格式模式。
简单地将输入解析为 Instant
对象。 Instant
表示 UTC 中的时刻,偏移量为零。
Instant.parse
方法使用常量 DateTimeFormatter.ISO_INSTANT
中的预定义格式化程序.
Instant instant4 = Instant.parse("2021-06-22T18:27:03.5577Z") ;
Instant instant5 = Instant.parse("2021-06-22T18:27:03.55770Z") ;
Instant instant6 = Instant.parse("2021-06-22T18:27:03.557700Z") ;
Instant instant7 = Instant.parse("2021-06-22T18:27:03.5577000Z") ;
Instant instant8 = Instant.parse("2021-06-22T18:27:03.55770000Z") ;
查看此 code run live at IdeOne.com .
2021-06-22T18:27:03.557700Z
2021-06-22T18:27:03.557700Z
2021-06-22T18:27:03.557700Z
2021-06-22T18:27:03.557700Z
如果想知道 ISO_INSTANT
是如何用 OpenJDK 编写的,see the source code .
关于java - 无法在索引 20 处解析文本 '2021-06-22T18:27:03.5577Z',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68411113/