java设置时间毫秒为0,Java:当秒和毫秒都是0时,DateTimeFormatter无法解析时间字符串?...

Basically, 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.

Solution

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值