Java:当秒和毫秒都是0时,DateTimeFormatter无法解析时间字符串? [英] Java: DateTimeFormatter fail to parse time string when seconds and milliseconds are all 0s?

查看:2116
本文介绍了Java:当秒和毫秒都是0时,DateTimeFormatter无法解析时间字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我使用以下代码将字符串解析为LocalDateTime,它在大多数情况下都能正常工作。

Basically, I am using the following code to parse string as LocalDateTime, which works fine most of the time.

DateTimeFormatter dtformatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");

但是,遇到秒和毫秒为 00000 ,这是解析器失败并打印 LocalDateTime 2018-03-01T09:16 而不是 2018-03-01T09:16:00.000

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));

(请注意,在我的代码中,我必须将字符串解析为 LocalDateTime ,做一些比较,然后在最后,打印 LocalDateTime 到csv)

(Note that in my code, I have to parse string as LocalDateTime, do some comparison and then at the end, print LocalDateTime to csv)

如何我可以修复它以使其打印 2018-03-01T09:16:00.000 而不是 2018-03-01T09:16

How can I fix it to make it print 2018-03-01T09:16:00.000 instead of 2018-03-01T09:16 ?

仅供参考,我使用的是jdk10。

FYI, I am using jdk10.

推荐答案

我不确定为什么它不起作用,它似乎是 bug 因为当我使用时:

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
----------------^                       -----------------^^^^^^

另外一个测试:

2018030100000000         result is      2018-03-01T00:00
--------^^^-----                        -----------^^^^^^^^^^^

似乎解析器会忽略毫秒ond 当它为零时,为什么?

It seems that the parser ignore the seconds and millisecond when it is zero, why?

完整的解释为什么?,是巴西尔布尔克

这是一个快速修复,你可以使用这样的另一个格式化程序:

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"));

输出

2018-03-01T09:16:00:000

这篇关于Java:当秒和毫秒都是0时,DateTimeFormatter无法解析时间字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆