SimpleDateFormat Parsing Time and Date wrong minutes and seconds

后端 未结 2 538
迷失自我
迷失自我 2021-01-15 20:37

Can anyone explain to me what\'s wrong in this code:

System.out.println(new SimpleDateFormat(\"yyyy-MM-dd\'T\'HH:mm:ss.sss\'Z\'\").parse(\"2015-04-22T19:54:1         


        
2条回答
  •  一个人的身影
    2021-01-15 20:43

    For SimpleDateFormat, the milliseconds format value contains capital S characters, not lowercase s characters for seconds.

    s Second in minute Number 55

    S Millisecond Number 978

    It's interpreting 827 as seconds, and adds those seconds (847 seconds is 13 minutes, 47 seconds) to your value.

    Use SSS for milliseconds.

    new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
    

    As an aside, you don't need to re-create your SimpleDateFormat more than once if it's the same. You can create it once, save it to a variable, and call parse multiple times, once for each date/time string you wish to parse.

提交回复
热议问题