`

使用java.util.Calendar返回间隔天数

阅读更多
java 代码
 
  1. **  
  2. * Calculates the number of days between two calendar days in a manner  
  3. * which is independent of the Calendar type used.  
  4. *  
  5. @param d1    The first date.  
  6. @param d2    The second date.  
  7. *  
  8. @return      The number of days between the two dates.  Zero is  
  9. *              returned if the dates are the same, one if the dates are  
  10. *              adjacent, etc.  The order of the dates  
  11. *              does not matter, the value returned is always >= 0.  
  12. *              If Calendar types of d1 and d2  
  13. *              are different, the result may not be accurate.  
  14. */  
  15. static int getDaysBetween (java.util.Calendar d1, java.util.Calendar d2) {  
  16.     if (d1.after(d2)) {  // swap dates so that d1 is start and d2 is end  
  17.         java.util.Calendar swap = d1;  
  18.         d1 = d2;  
  19.         d2 = swap;  
  20.     }  
  21.     int days = d2.get(java.util.Calendar.DAY_OF_YEAR) -  
  22.                d1.get(java.util.Calendar.DAY_OF_YEAR);  
  23.     int y2 = d2.get(java.util.Calendar.YEAR);  
  24.     if (d1.get(java.util.Calendar.YEAR) != y2) {  
  25.         d1 = (java.util.Calendar) d1.clone();  
  26.         do {  
  27.             days += d1.getActualMaximum(java.util.Calendar.DAY_OF_YEAR);  
  28.             d1.add(java.util.Calendar.YEAR, 1);  
  29.         } while (d1.get(java.util.Calendar.YEAR) != y2);  
  30.     }  
  31.     return days;  
  32. }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics