Decrease date in Java

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

for example, if the current time is Date currentTime = new Date();

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

How to determine the time ie

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

+7
source share
4 answers

You can do this using the 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 
+25
source

I would advise you to use Joda Time to get started, which is a much better API. Then you can use:

 DateTime yesterday = new DateTime().minusDays(1); 

Note that “this time yesterday” is not always 24 hours ago, though ... you need to think about time zones, etc. You can use LocalDateTime or Instant instead of DateTime .

+10
source

24 hours and 1 day are not the same thing. But both of you use Calendar:

 Calendar c = Calendar.getInstance(); c.setTime(new Date()); c.add(Calendar.DATE, -1); Date d = c.getTime(); 

If you return for 24 hours, you should use Calendar.HOUR_OF_DAY

+1
source

please check this here: Java Date vs. Calendar

 Calendar cal=Calendar.getInstance(); cal.setTime(date); //not sure if date.getTime() is needed here cal.add(Calendar.DAY_OF_MONTH, -1); Date newDate = cal.getTime(); 
+1
source

All Articles