java 日期计算(几天前后)

来源:互联网 发布:linux下vim环境配置 编辑:程序博客网 时间:2024/06/09 23:44
  1. public class DateTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Date date = new Date(); // 新建一个日期  
  5.   
  6.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 格式化日期  
  7.   
  8.         String beforeDate = sdf.format(getDateBefore(date, 10));  
  9.         System.out.println(beforeDate);  
  10.         String afterDate = sdf.format(getDateAfter(date, 10));  
  11.         System.out.println(afterDate);  
  12.     }  
  13.   
  14.     /** 
  15.      * 得到几天前的时间 
  16.      */  
  17.   
  18.     public static Date getDateBefore(Date d, int day) {  
  19.         Calendar now = Calendar.getInstance();  
  20.         now.setTime(d);  
  21.         now.set(Calendar.DATE, now.get(Calendar.DATE) - day);  
  22.         return now.getTime();  
  23.     }  
  24.   
  25.     /** 
  26.      * 得到几天后的时间 
  27.      */  
  28.       
  29.     public static Date getDateAfter(Date d, int day) {  
  30.         Calendar now = Calendar.getInstance();  
  31.         now.setTime(d);  
  32.         now.set(Calendar.DATE, now.get(Calendar.DATE) + day);  
  33.         return now.getTime();  
  34.     }  
  35. }  
转载自:http://lshh83.iteye.com/blog/366937

0 0
原创粉丝点击