javadatetimedateutilities

Decrement a date in Java


I want to get the previous day (24 hours) from the current time.

e.g if current time is Date currentTime = new Date();

2011-04-25 12:15:31:562 GMT

How to determine time i.e

2011-04-24 12:15:31:562 GMT


Solution

  • You can do that using Calendar class:

    Calendar cal = Calendar.getInstance();
    cal.setTime ( date ); // convert your date to Calendar object
    int daysToDecrement = -1;
    cal.add(Calendar.DATE, daysToDecrement);
    date = cal.getTime(); // again get back your date object