public class DateTest {
public static void main(String[] args) {
Date date = new Date(); // 新建一个日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 格式化日期
String beforeDate = sdf.format(getDateBefore(date, 10));
System.out.println(beforeDate);
String afterDate = sdf.format(getDateAfter(date, 10));
System.out.println(afterDate);
}
/**
* 得到几天前的时间
*/
public static Date getDateBefore(Date d, int day) {
Calendar now = Calendar.getInstance();
now.setTime(d);
now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
return now.getTime();
}
/**
* 得到几天后的时间
*/
public static Date getDateAfter(Date d, int day) {
Calendar now = Calendar.getInstance();
now.setTime(d);
now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
return now.getTime();
}
}