Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a Java Date object's value to yesterday? [duplicate]

Tags:

java

Possible Duplicate:
Get yesterday's date using Date

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

like image 468
prilia Avatar asked Aug 15 '12 08:08

prilia


3 Answers

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.

like image 60
Peter Lawrey Avatar answered Oct 20 '22 19:10

Peter Lawrey


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"));
like image 38
Eugene Avatar answered Oct 20 '22 19:10

Eugene


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.

like image 28
Sanjay T. Sharma Avatar answered Oct 20 '22 18:10

Sanjay T. Sharma