Java: DateTimeFormatter fail to parse time string when seconds and milliseconds are all 0s?

前端 未结 2 1836
感情败类
感情败类 2020-12-11 05:43

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

DateTimeFormatter dtformatter = DateTimeFormat         


        
2条回答
  •  温柔的废话
    2020-12-11 06:00

    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
    

提交回复
热议问题