获取两个时间内的日期集合


已知两个日期,循环出 [timeStart - timeEnd] 的所有日期,包括开始和结束时间。 并存入一个List<String>的集合中 代码如下


package com.test.dateTest;



import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


public class Test4 {


public static void main(String[] args) {
String date = "2016-12-16";
String date2 = "2016-12-13";
try {
List<String> list = getDatesBetweenTwoDate(date, date2);
System.out.println("两者相差:::"+list+"天");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 根据开始时间和结束时间返回时间段内的时间集合
* @param beginDate
* @param endDate
* @return List<String>
*/
public static List<String> getDatesBetweenTwoDate(String beginDate1, String endDate1) throws Exception{ 
Date beginDate;
Date endDate;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
beginDate = format.parse(beginDate1);
endDate = format.parse(endDate1);
   List<String> dateList = new ArrayList<String>();
   dateList.add(beginDate1);//把开始时间加入集合
   Calendar cal = Calendar.getInstance();
   //使用给定的 Date 设置此 Calendar 的时间
   cal.setTime(beginDate);
   if(cal.getTime().after(endDate)){
    throw new RuntimeException("开始时间大于结束时间");
   }
   boolean bContinue = true;
   while (bContinue) {
       //根据日历的规则,为给定的日历字段添加或减去指定的时间量
       cal.add(Calendar.DAY_OF_MONTH, 1);
       // 测试此日期是否在指定日期之后
       if (endDate.after(cal.getTime())) {
        dateList.add(format.format(cal.getTime()));
       } else {
           break;
       }
   }
   dateList.add(endDate1);//把结束时间加入集合
   return dateList;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值