在最近的项目中,有这么一个需求,根据开始时间、结束时间得到两个时间段内所有的日期,以下分享我的代码给大家。

1、以下的这个方法适用于jdk1.5以上的版本


 
  
  1. /**  
  2. * 根据开始时间和结束时间返回时间段内的时间集合  
  3. * @param beginDate  
  4. * @param endDate  
  5. * @return List  
  6. */  
  7. @SuppressWarnings("unchecked")  
  8. public static List getDatesBetweenTwoDate(Date beginDate, Date endDate) {  
  9. List lDate = new ArrayList();  
  10. lDate.add(beginDate);//把开始时间加入集合  
  11. Calendar cal = Calendar.getInstance();  
  12. //使用给定的 Date 设置此 Calendar 的时间  
  13. cal.setTime(beginDate);  
  14. boolean bContinue = true;  
  15. while (bContinue) {  
  16. //根据日历的规则,为给定的日历字段添加或减去指定的时间量  
  17. cal.add(Calendar.DAY_OF_MONTH, 1);  
  18. // 测试此日期是否在指定日期之后  
  19. if (endDate.after(cal.getTime())) {  
  20. lDate.add(cal.getTime());  
  21. else {  
  22. break;  
  23. }  
  24. }  
  25. lDate.add(endDate);//把结束时间加入集合  
  26. return lDate;  
  27. }  

2、以下的方法适用于jdk1.4以下的版本



 
  
  1. /** 
  2. * 根据开始时间和结束时间返回时间段内的时间集合 
  3. * @param beginDate 
  4. * @param endDate 
  5. * @return List 
  6. */ 
  7. public static List getDatesBetweenTwoDate(Date beginDate, Date endDate) { 
  8. List lDate = new ArrayList(); 
  9. lDate.add(beginDate);//把开始时间加入集合 
  10. Calendar cal = Calendar.getInstance(); 
  11. //使用给定的 Date 设置此 Calendar 的时间 
  12. cal.setTime(beginDate); 
  13. boolean bContinue = true
  14. while (bContinue) { 
  15. //根据日历的规则,为给定的日历字段添加或减去指定的时间量 
  16. cal.add(Calendar.DAY_OF_MONTH, 1); 
  17. // 测试此日期是否在指定日期之后 
  18. if (endDate.after(cal.getTime())) { 
  19. lDate.add(cal.getTime()); 
  20. else { 
  21. break
  22. lDate.add(endDate);//把结束时间加入集合 
  23. return lDate; 

3、调用测试


 
  
  1. public static void main(String[] args)throws Exception{ 
  2. System.out.println("jdk1.6测试"); 
  3. Calendar cal = Calendar.getInstance(); 
  4. String start = "2012-01-03"
  5. String end = "2012-03-05"
  6. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
  7. Date dBegin =sdf.parse(start); 
  8. Date dEnd = sdf.parse(end); 
  9. List listDate = getDatesBetweenTwoDate(dBegin, dEnd); 
  10. for(Date date:listDate){ 
  11. System.out.println(sdf.format(date)); 
  12. System.out.println("jdk1.4测试"); 
  13. List lDate = getDatesBetweenTwoDate(dBegin, dEnd); 
  14. for(int i=0;i Date date = (Date)lDate.get(i); 
  15. System.out.println(sdf.format(date));