SimpleDateFormat is not parsing the milliseconds correctly

前端 未结 4 2008
臣服心动
臣服心动 2020-12-10 10:33

Background:

In my database table, I have two timestamps

timeStamp1 = 2011-08-23 14:57:26.662
timeStamp2 = 2011-08-23 14:57:26.9
         


        
4条回答
  •  悲哀的现实
    2020-12-10 11:04

    I had the same problem with too accurate time from my logfiles with 6 digit milliseconds. Parsing Time gave up to 16 minutes difference! WTF?

    16-JAN-12 04.00.00.999999 PM GMT --> 16 Jan 2012 04:16:39 GMT
    

    Changing the number of digits reduced the erroneous difference and thanks to this thread I could identify the problem:

    16-JAN-12 04.00.00.99999 PM GMT --> 16 Jan 2012 04:01:39 GMT
    16-JAN-12 04.00.00.9999 PM GMT --> 16 Jan 2012 04:00:09 GMT
    16-JAN-12 04.00.00.999 PM GMT --> 16 Jan 2012 04:00:00 GMT
    

    As SimpleDateFormat internally handles only 3 digits I removed the unnecessary with a small regex (ignoring round-off errors, working for 1 up to n digits):

    str = str.replaceAll("(\\.[0-9]{3})[0-9]*( [AP]M)", "$1$2");
    

    Thanks to @Peter Lawrey for your answer, prevented me going insane :-)

提交回复
热议问题