Calculate Date/Time Difference in Java considering AM/PM

前端 未结 6 557
陌清茗
陌清茗 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条回答
  •  抹茶落季
    2020-12-16 05:29

    So, you have these dates as strings? Parse them with a SimpleDateFormat with the appropriate format string, and compute the difference in hours:

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
    
    Date d1 = df.parse("2012-01-24 12:30:00 PM");
    Date d2 = df.parse("2012-01-24 02:30:00 PM");
    
    int hoursDifference = (int)((d2.getTime() - d1.getTime()) / 3600000L);
    System.out.println("Difference in hours: " + hoursDifference);
    

    Your error is that you are using HH (24-hour hours) instead of hh (12-hour hours) in your format string.

提交回复
热议问题