基本上,我使用以下代码将字符串解析为 LocalDateTime,这在大多数情况下都可以正常工作.
DateTimeFormatter dtformatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");但是,我遇到秒和毫秒为 00000 的情况,这是解析器失败并打印 LocalDateTime 2018-03-01T09:16 而不是 2018-03-01T09:16:00.000.
System.out.println(LocalDateTime.parse("20180301091600000",dtformatter));(请注意,在我的代码中,我必须将字符串解析为 LocalDateTime,进行一些比较,然后最后将 LocalDateTime 打印到 csv)
如何修复它以使其打印 2018-03-01T09:16:00.000 而不是 2018-03-01T09:16 ?
仅供参考,我正在使用 jdk10.
我不知道为什么它不起作用,它似乎是一个 bug 因为当我使用:
20180301091600001 结果是 2018-03-01T09:16:00.001----------------^ -----------------^^^^^^还有另一个测试:
2018030100000000 结果是 2018-03-01T00:00--------^^^------------------^^^^^^^^^^^解析器好像忽略了秒和毫秒为零的时候,为什么?
为什么?的完整解释在 Basil Bourque 的回答中.p>
这是一个快速修复,您可以使用其他格式化程序,如下所示:
var 结果 = LocalDateTime.parse("20180301091600000", dtformatter).format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss:SSS"));输出
2018-03-01T09:16:00:000Basically, I am using the following code to parse string as LocalDateTime, which works fine most of the time.
DateTimeFormatter dtformatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
However, I encounter cases where the seconds and millseconds are 00000 and this is when the parser fails and print a LocalDateTime 2018-03-01T09:16 instead of 2018-03-01T09:16:00.000.
System.out.println(LocalDateTime.parse("20180301091600000",dtformatter));
(Note that in my code, I have to parse string as LocalDateTime, do some comparison and then at the end, print LocalDateTime to csv)
How can I fix it to make it print 2018-03-01T09:16:00.000 instead of 2018-03-01T09:16 ?
FYI, I am using jdk10.
I'm not sure why it's not work, it seems it is a bug because when I use :
20180301091600001 result is 2018-03-01T09:16:00.001
----------------^ -----------------^^^^^^
Also another test :
2018030100000000 result is 2018-03-01T00:00
--------^^^----- -----------^^^^^^^^^^^
It seems that the parser ignore the seconds and millisecond when it is zero, why?
The full explanation why?, is in the answer of Basil Bourque.
Here is a quick fix where you can use another formatter like this :
var result = LocalDateTime.parse("20180301091600000", dtformatter)
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss:SSS"));
Output
2018-03-01T09:16:00:000
这篇关于Java:当秒和毫秒都为 0 时,DateTimeFormatter 无法解析时间字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何检测 32 位 int 上的整数溢出?How can I detect integer overflow on 32 bits int?(如何检测 32 位 int 上的整数溢出?)
return 语句之前的局部变量,这有关系吗?Local variables before return statements, does it matter?(return 语句之前的局部变量,这有关系吗?)
如何将整数转换为整数?How to convert Integer to int?(如何将整数转换为整数?)
如何在给定范围内创建一个随机打乱数字的 intHow do I create an int array with randomly shuffled numbers in a given range(如何在给定范围内创建一个随机打乱数字的 int 数组)
java的行为不一致==Inconsistent behavior on java#39;s ==(java的行为不一致==)
为什么 Java 能够将 0xff000000 存储为 int?Why is Java able to store 0xff000000 as an int?(为什么 Java 能够将 0xff000000 存储为 int?)