Inconsistent date parsing using SimpleDateFormat

后端 未结 4 1118
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-17 20:14

I\'m really scratching my head on this one. I\'ve been using SimpleDateFormats with no troubles for a while, but now, using a SimpleDateFormat to parse dates is

4条回答
  •  攒了一身酷
    2020-12-17 21:04

    You're printing out the toString() representation of the date, rather than the format's representation. You may also want to check the hour representation. H and h mean something different. H is for the 24 hour clock (0-23), h is for the 12 hour clock (1-12), (there is also k and K for 1-24 and 0-11 based times respectively)

    You need to do something like:

    //in reality obtain the date from elsewhere, e.g. new Date()
    Date date = sdf.parse("2009-08-19 12:00:00"); 
    
    //this format uses 12 hours for time
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    //this format uses 24 hours for time
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    System.out.print(sdf.format(date));
    System.out.print(sdf2.format(date));
    

提交回复
热议问题