问题
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.
回答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.
回答2:
You can also use Joda-Time, a very good Java library to manipulate dates:
DateTime result = dt.minusDays(1);
回答3:
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);
回答4:
With java.time.Instant
Date.from(Instant.now().minus(Duration.ofDays(1)))
回答5:
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
}
}
回答6:
With the date4j library :
DateTime yesterday = today.minusDays(1);
回答7:
This would help.
getPreviousDateForGivenDate("2015-01-19", 10);
getPreviousDateForGivenDate("2015-01-19", -10);
public static String getPreviousDateForGivenDate(String givenDate, int datesPriorOrAfter) {
String saleDate = getPreviousDate(datesPriorOrAfter);
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String[] arr = givenDate.split("-", 3);
Calendar cal = new GregorianCalendar(Integer.parseInt(arr[0]), Integer.parseInt(arr[1])-1, Integer.parseInt(arr[2]));
cal.add(Calendar.DAY_OF_YEAR, datesPriorOrAfter);
saleDate = dateFormat.format(cal.getTime());
} catch (Exception e) {
System.out.println("Error at getPreviousDateForGivenDate():"+e.getMessage());
}
return saleDate;
}
来源:https://stackoverflow.com/questions/745443/how-to-determine-the-date-one-day-prior-to-a-given-date-in-java