java 日期计算(几天前后)

来源:互联网 发布:java登录界面图片 编辑:程序博客网 时间:2024/04/29 10:43

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();
 }
}