javaandroiddatesimpledateformatdatetime-parsing

SimpleDateFormat Parsing Time and Date wrong minutes and seconds


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:11.827Z"));

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

Out put is:

Wed Apr 22 20:07:47 GMT+02:00 2015
Wed Apr 22 19:54:00 GMT+02:00 2015

Please notice the difference in minutes when there are milli seconds in the input time.


Solution

  • 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.