java 日期前後推算計算

  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.     }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章