SimpleDateFormat Parsing Time and Date wrong minutes and seconds

后端 未结 2 510
迷失自我
迷失自我 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.

    0 讨论(0)
  • 2021-01-15 21:05

    Use capital SSS instead of sss, as s is interpreted as seconds in SimpleDateFormat. So change your code to

    System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse("2015-04-22T19:54:11.827Z"));
    
    System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse("2015-04-22T19:54:11.0Z"));
    

    This shall do the job for you. And in order to optimize your code use this

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    System.out.println(sdf.parse("2015-04-22T19:54:11.827Z"));
    
    System.out.println(sdf.parse("2015-04-22T19:54:11.0Z"));
    

    No need to create objects again and again. Just create once and use that to parse.

    0 讨论(0)
提交回复
热议问题