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.
Use the setDate() method to get the previous day of a date, e.g. date. setDate(date. getDate() - 1) .
In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.
oneDayBefore = new Date(myDate. getTime() - 2); String result = dateFormat. format(oneDayBefore); To get the same results as those that are being computed by using Calendar.
DateTime yesterday = new DateTime(). minusDays(1);
Use the Calendar interface.
Calendar cal = Calendar.getInstance();
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. This is valid for 1st of the year as well, e.g. if myDate
is January 1st, 2012, oneDayBefore
will be December 31st, 2011.
You can also use Joda-Time, a very good Java library to manipulate dates:
DateTime result = dt.minusDays(1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With