views:

669

answers:

4

I am assuming Java has some built-in way to do this.

Given a date, how can I determine the date one day prior to that date?

For example, suppose I am given 3/1/2009. The previous date is 2/28/2009. If I had been given 3/1/2008, the previous date would have been 2/29/2008.

+18  A: 

Use the Calendar interface.

Calendar cal = new GregorianCalendar();
cal.setTime(myDate);
cal.add(Calendar.DAY_OF_YEAR,-1);
Date oneDayBefore= cal.getTime();

Doing "addition" in this way guarantees you get a valid date.

Mike Pone
Exactly what I was looking for. Thanks!
William Brendel
+1  A: 

The java.util.Calendar class allows us to add or subtract any number of day/weeks/months/whatever from a date. Just use the add() method:

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html

Example:

Calendar date = new GregorianCalendar(2009, 3, 1);
date.add(Calendar.DATE, -1);
marcog
A: 
import java.util.Calendar;
import java.util.GregorianCalendar;
import static java.util.Calendar.*;


public class TestDayBefore {

    public static void main(String... args) {
     Calendar calendar = GregorianCalendar.getInstance();
     calendar.set(YEAR, 2009);
     calendar.set(MONTH, MARCH);
     calendar.set(DAY_OF_MONTH, 1);
     System.out.println(calendar.getTime()); //prints Sun Mar 01 23:20:20 EET 2009
     calendar.add(DAY_OF_MONTH, -1);
     System.out.println(calendar.getTime()); //prints Sat Feb 28 23:21:01 EET 2009

    }
}
MahdeTo
+2  A: 

You can also use Joda-Time, a very good Java library to manipulate dates:

DateTime result = dt.minusDays(1);
Vladimir