SimpleDateFormat Parsing Time and Date wrong minutes and seconds

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

提交回复
热议问题