Search code examples
javatimegregorian-calendar

How do you do you adjust Gregorian Calendar date so that it is 24, 48 and 78 hours before using HOUR_OF_DAY


I am wanting to adjust 3 Gregorian Calendar dates in Java, with one to be 24 hours before, the other 48, hours before and last 78 hours before. I had been using Calendar.HOUR and changed this to Calendar.HOUR_OF_DAY.

Since I did this my code stopped working. I am comparing the adjusted dates with their original values using a method that uses date1.before(date2) and date1.after(date2) to get a comparisonflag which can be 1 or 0 which I then use in my code.

I was wondering how to do the adjust the HOUR_OF_DAY in my dates to then achieve the above.


Solution

  • Some code would have been nice. But if I understand the problem correctly:

    From the javadoc of Calendar:

    HOUR is used for the 12-hour clock. E.g., at 10:04:15.250 PM the HOUR is 10.
    HOUR_OF_DAY is used for the 24-hour clock. E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22.
    

    When adding/substracting hours from a date:

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR, -24);
    cal.add(Calendar.HOUR_OF_DAY, -24);
    

    This should have the same effect.