您的位置 首页 java

java中一个补全开始到结束时间的工具方法

 /**
 * 补全开始到结束时间的工具方法
 */public List<String> testDateUtils(String startTime,String endTime) throws Exception {

   /*startTime="2021-02-03";
   endTime="2021-02-06";*/
   if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
      throw new Exception("开始日期和截止日期都不能为空!");
   }
   //compareTo 当两者相等时为0,当前者小于后者时返回-1,大于时返回1。具体查看源码。
   if (startTime.compareTo(endTime)>0){
      throw new Exception("开始日期必须小于等于截止日期!");
   }

   SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
   Date startDate = simpleDateFormat.parse(startTime);
   Date endDate = simpleDateFormat.parse(endTime);

   Calendar startCal = Calendar.getInstance();
   Calendar endCal = Calendar.getInstance();
   startCal.setTime(startDate);
   endCal.setTime(endDate);

   List<String> days = new ArrayList<>();
   //当开始时间大于结束时间时则返回
   while (startCal.compareTo(endCal)<=0) {
      days.add(simpleDateFormat.format(startCal.getTime()));
      //Date本身加减日期过于麻烦,使用Calendar操纵日期;开始时间+1;
      startCal.add(Calendar.DATE,1);

   }
   return days;

}  

文章来源:智云一二三科技

文章标题:java中一个补全开始到结束时间的工具方法

文章地址:https://www.zhihuclub.com/189151.shtml

关于作者: 智云科技

热门文章

网站地图