7

Possible Duplicate:
Get yesterday's date using Date

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

1

6 Answers 6

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")); 
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for using JodaTime instead of Date.
Java 8 LocalDate is very similar: LocalDate.now().minusDays( 1 )
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.

Comments

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.

Comments

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())); 

3 Comments

That looks similar to @UVM's answer. Can you try adding something his answer doesn't?
@PeterLawrey I tested and it's worked fine
I know its fine, its just that its much the same as an earlier posting.
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

Comments

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())); 

2 Comments

That seems very complicated. Can you simplify the example?
@PeterLawrey, I have just made more simpler.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.