7

Possible Duplicate:
Get yesterday's date using Date

What is an elegant way set to a Java Date object's value to yesterday?

Community
  • 1
  • 1
prilia
  • 996
  • 5
  • 18
  • 41

6 Answers6

19

With JodaTime

  LocalDate today = LocalDate.now();
    LocalDate yesterday = today.minus(Period.days(1));

    System.out.printf("Today is : %s, Yesterday : %s", today.toString("yyyy-MM-dd"), yesterday.toString("yyyy-MM-dd"));
Eugene
  • 117,005
  • 15
  • 201
  • 306
18

Do you mean to go back 24 hours in time.

 Date date = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000L);

or to go back one day at the time same time (this can be 23 or 25 hours depending on daylight savings)

 Calendar cal = Calendar.getInstance();
 cal.add(Calendar.DATE, -1); 

These are not exactly the same due to daylight saving.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

Convert the Date to a Calendar object and "roll" it back a single day. Something like this helper method take from here:

public static void addDays(Date d, int days)
{
    Calendar c = Calendar.getInstance();
    c.setTime(d);
    c.add(Calendar.DATE, days);
    d.setTime(c.getTime().getTime());
}

For your specific case, just pass in days as -1 and you should be done. Just make sure you take into consideration the timezone/locale if doing extensive date specific manipulations.

Community
  • 1
  • 1
Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71
0

You can try the following example to set it to previous date.

Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("Today's date is " +dateFormat.format(cal.getTime()));    
cal.add(Calendar.DATE, -1);  
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));
Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
UVM
  • 9,776
  • 6
  • 41
  • 66
0
you can try the follwing code:
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today's date is "+dateFormat.format(cal.getTime()));

cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime())); 
bouazizi
  • 31
  • 3
0

As many people have already said use Calendar rather than date.

If you find you really want to use dates:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -24);
cal.getTime();//returns a Date object

Calendar cal1 = Calendar.getInstance();
cal1.add(Calendar.DAY_OF_MONTH, -1);
cal1.getTime();//returns a Date object

I hope this helps. tomred

TomRed
  • 503
  • 5
  • 7