计算两个日期之间的天数:
public static void main(String[] args) throws ParseException { String startTime = "2019-11-30"; String endTime = "2019-12-12"; Calendar startCal = Calendar.getInstance(); Calendar endCal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date startDate = sdf.parse(startTime); Date endDate = sdf.parse(endTime); startCal.setTime(startDate); endCal.setTime(endDate); List<String> list = new ArrayList<>(); //得到两个日期相差的天数 还可通过去除后面的数 求得相差的小时数,分钟数,秒 等等 int days = ((int)(endCal.getTime().getTime()/1000)-(int)(startCal.getTime().getTime()/1000))/3600/24; for(int i = 0;i<=days;i++){ list.add(sdf.format(startCal.getTime())); startCal.add(Calendar.DAY_OF_MONTH, 1); } System.out.println(days); System.out.println(list); }
/**
* startTime 起始日期
* endTime 截止日期
* dateType 日期类型 HOUR/DAY/MONTH/YEAR
*/
public Integer dateTimeNums(String startTime,String endTime,String dateType) throws ParseException{
String fmtStr = null;
int timeNum = 3600 * 24;
switch(dateType){
case "HOUR" :
fmtStr = "yyyy-MM-dd HH";
timeNum = 3600;
break;
case "DAY" :
fmtStr = "yyyy-MM-dd";
timeNum = 3600 * 24 ;
break;
case "MONTH" :
fmtStr = "yyyy-MM";
timeNum = 3600 * 24 * 30;
break;
case "YEAR" :
fmtStr = "yyyy";
timeNum = 3600 * 24 * 365 ;
break;
default :
fmtStr = "yyyy-MM-dd";
break;
}
Calendar startCal = Calendar.getInstance();
Calendar endCal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(fmtStr);//此处修改日期格式
Date startDate = sdf.parse(startTime);
Date endDate = sdf.parse(endTime);
startCal.setTime(startDate);
endCal.setTime(endDate);
startCal.compareTo(endCal);
//得到两个日期相差的天数
int nums = ((int)(endCal.getTime().getTime()/1000)-(int)(startCal.getTime().getTime()/1000))/timeNum;//此处修改日期单位
return nums;
}