Calendar的add()方法介紹


由於項目當中要統計指定日期的日志記錄,是使用Calendar的add方法來進行對日期參數進行相關的動態改變。但是看了java doc上面介紹的不是很清楚,只是說了一下add能夠做什么事,並沒有介紹如何具體實現。看了網上的一些資料大部分都是在講add和roll兩個方法的區別,其實我們只需要使用add方法就可以解決大部分的功能。比如我們需要得到當前年,月,日,小時,分鍾,秒,毫秒的前面時間或者后面時間,使用add方法如何實現呢?一開始我也不知道,問了技術總監他給了我一段代碼讓我自己去試驗,代碼如下:

 

 

[java]  view plain  copy
 
  1. public static Date addYears(Date date, int amount)    
  2.     {    
  3.         return add(date, 1, amount);    
  4.     }    
  5.     
  6.     public static Date addMonths(Date date, int amount)    
  7.     {    
  8.         return add(date, 2, amount);    
  9.     }    
  10.     
  11.     public static Date addWeeks(Date date, int amount)    
  12.     {    
  13.         return add(date, 3, amount);    
  14.     }    
  15.     
  16.     public static Date addDays(Date date, int amount)    
  17.     {    
  18.         return add(date, 5, amount);    
  19.     }    
  20.     
  21.     public static Date addHours(Date date, int amount)    
  22.     {    
  23.         return add(date, 11, amount);    
  24.     }    
  25.     
  26.     public static Date addMinutes(Date date, int amount)    
  27.     {    
  28.         return add(date, 12, amount);    
  29.     }    
  30.     
  31.     public static Date addSeconds(Date date, int amount)    
  32.     {    
  33.         return add(date, 13, amount);    
  34.     }    
  35.     
  36.     public static Date addMilliseconds(Date date, int amount)    
  37.     {    
  38.         return add(date, 14, amount);    
  39.     }    
  40.     
  41.     private static Date add(Date date, int calendarField, int amount)    
  42.     {    
  43.         if(date == null)    
  44.         {    
  45.             throw new IllegalArgumentException("The date must not be null");    
  46.         } else    
  47.         {    
  48.             Calendar c = Calendar.getInstance();    
  49.             c.setTime(date);    
  50.             c.add(calendarField, amount);    
  51.             return c.getTime();    
  52.         }    
  53.     }  


我在一個測試類中測試了一下,如果是1則代表的是對年份操作,2是對月份操作,3是對星期操作,5是對日期操作,11是對小時操作,12是對分鍾操作,13是對秒操作,14是對毫秒操作。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM