Decrement a date in Java

Muhammad Imran Tariq picture Muhammad Imran Tariq · Apr 27, 2011 · Viewed 18.9k times · Source

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

Answer

anubhava picture anubhava · Apr 27, 2011

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