1.计算两个日期之间的天数:
1 /** 2 *计算两个日期之间的天数 3 *@param startDate 4 *@param endDate 5 *@return 天数 6 */ 7 public static Integer daysBetween(String startDate,String endDate) throws Exception{ 8 SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd"); 9 Calendar cal = Calendar.getInstance(); 10 cal.setTime(sd.parse(startDate)); 11 long time1 = cal.getTimeInMillis(); 12 cal.setTime(sd.parse(endDate)); 13 long time2 = cal.getTimeInMillis(); 14 long between_days=(time2-time1)/(1000*3600*24); 15 return Integer.parseInt(String.valueOf(between_days)); 16 }
示例:开始日期:2021-08-01 ,结束日期:2021-08-16,之间的天数:15
2.获取某段时间内的周几的日期
1 /** 2 * 获取某段时间内的周一(二等等)的日期 3 * @param dataBegin 开始日期 4 * @param dataEnd 结束日期 5 * @param weekDays 获取周几,1-6代表周一到周六。0代表周日 6 * @return 返回日期List 7 */ 8 public static List<String> getDayOfWeekWithinDateInterval(String dataBegin, String dataEnd, int weekDays) { 9 SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd"); 10 List<String> dateResult = new ArrayList<>(); 11 Calendar cal = Calendar.getInstance(); 12 String[] dateInterval = {dataBegin, dataEnd}; 13 Date[] dates = new Date[dateInterval.length]; 14 for (int i = 0; i < dateInterval.length; i++) { 15 String[] ymd = dateInterval[i].split("[^\d]+"); 16 cal.set(Integer.parseInt(ymd[0]), Integer.parseInt(ymd[1]) - 1, Integer.parseInt(ymd[2])); 17 dates[i] = cal.getTime(); 18 } 19 for (Date date = dates[0]; date.compareTo(dates[1]) <= 0; ) { 20 cal.setTime(date); 21 if (cal.get(Calendar.DAY_OF_WEEK) - 1 == weekDays) { 22 String format = sd.format(date); 23 dateResult.add(format); 24 } 25 cal.add(Calendar.DATE, 1); 26 date = cal.getTime(); 27 } 28 return dateResult; 29 }
示例:开始日期:2021-08-01 到 结束日期:2021-08-16 之间的周一的天数有:3天,日期分别为:2021-08-02 2021-08-09 2021-08-16