如果當前日期以字符串形式給出,如何查找以前的日期?下面給出我的代碼。有沒有更短的解決方案?如果當前日期以字符串形式給出,如何查找以前的日期?
private static String previousDay(String date) {
String[] ymd = date.split("-");
int year = Integer.parseInt(ymd[0]);
int month = Integer.parseInt(ymd[1]);
int day = Integer.parseInt(ymd[2]);
String newDate = "";
if (day > 1 & month > 1)
newDate = year+"-"+month+"-"+(day-1);
else if (day == 1 & month > 1) {
Calendar calendar = new GregorianCalendar(year,month-1, 1);
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
newDate = year+"-"+(month-1)+"-"+daysInMonth;
} else if (day == 1 & month == 1) {
Calendar calendar = new GregorianCalendar(year,12, 1);
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
newDate = year+"-"+12+"-"+daysInMonth;
}
return newDate;
}
嗯,我會使用SimpleDateFormat的字符串恢復到java.util.Date對象,然後使用它。很快就會發布代碼。 – BigMike
[如何在java中獲取上一個日期](http://stackoverflow.com/questions/2458049/how-to-get-previous-date-in-java) – dogbane