How to set the value of a Java Date object yesterday?

Possible duplicate:
Get yesterday's date using date

What is an elegant way to set the value of a Java Date object yesterday?

+4
source share
6 answers

You want to return 24 hours on time.

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

or return on the same day at the same time (it can be 23 or 25 hours depending on summer time)

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

This is not exactly the same due to summer time.

+13
source

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")); 
+14
source

Convert the Date object to a Calendar object and return it in one day. Something like this helper method takes 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 go to days as -1 , and you need to do this. Just make sure you consider the time zone / locale if you are doing specific date manipulations.

+1
source

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

 Calendar cal = Calendar.getInstance(); DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); System.out.println("Today date is " +dateFormat.format(cal.getTime())); cal.add(Calendar.DATE, -1); System.out.println("Yesterday date was "+dateFormat.format(cal.getTime())); 
0
source
 you can try the follwing code: Calendar cal = Calendar.getInstance(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); System.out.println("Today date is "+dateFormat.format(cal.getTime())); cal.add(Calendar.DATE, -1); System.out.println("Yesterday date was "+dateFormat.format(cal.getTime())); 
0
source

As already noted, many use a calendar rather than a date.

If 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 

Hope this helps. tomred

0
source

All Articles