Calculate Date/Time Difference in Java considering AM/PM

前端 未结 6 564
陌清茗
陌清茗 2020-12-16 04:33

I want to calculate the difference between two date/time in java using Date and Calendar classes. The format that I have is \"2012-01-24 12:30:00 PM\".

I have implem

6条回答
  •  旧时难觅i
    2020-12-16 05:35

    The reason why it shows 10 hours as the difference is that you've got an error in the pattern when parsing the input.

    Here's an example using SimpleDateFormat:

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
    
    Date date1 = df.parse("2012-01-24 12:30:00 PM");
    Date date2 = df.parse("2012-01-24 02:30:00 PM");
    
    long differenceInHours = Math.abs(date1.getTime() - date2.getTime()) / 1000 / 60 / 60);
    

    Will return 10.

    When we just slightly change the date format pattern, using hh for hour in am/pm (1-12) instead of HH for hour in day (0-23):

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
    

    It returns (the expected) 2.

    See the documentation for SimpleDateFormat to get your patterns right.

提交回复
热议问题