SimpleDateFormat is not parsing the milliseconds correctly

前端 未结 4 2010
臣服心动
臣服心动 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条回答
  •  旧时难觅i
    2020-12-10 10:57

    The format you are parsing and the format uses doesn't match. You expect a three digit field and are only providing one digits. It takes 9 and assumes you mean 009 when what you want is 900. Date formats are complicated and when you prove dates in a different format it may parse them differently to you.

    The documentation says S means the number of milli-seconds and the number in that field is 9, so it is behaving correctly.


    EDIT: This example may help

    final SimpleDateFormat ss_SSS = new SimpleDateFormat("ss.SSS");
    ss_SSS.setTimeZone(TimeZone.getTimeZone("GMT"));
    for (String text : "0.9, 0.456, 0.123456".split(", ")) {
      System.out.println(text + " parsed as \"ss.SSS\" is "
          + ss_SSS.parse(text).getTime() + " millis");
    }
    

    prints

    0.9 parsed as "ss.SSS" is 9 millis
    0.456 parsed as "ss.SSS" is 456 millis
    0.123456 parsed as "ss.SSS" is 123456 millis
    

提交回复
热议问题