日期工具类,持续更新,欢迎补充···
1)获取2个日期之间的所有日期, strDayList返回字符串,days返回日期类型
public Class DateUtils{
// 获取2个日期之间的所有日期, strDayList返回字符串,days返回日期类型
// 例:传入2024-01-01,2024-01-03,返回集合[2024-01-01,2024-01-02,2024-01-03]
public static List<String> getBetweenDaysStr(Date start, Date end) {
List<String> strDayList = new ArrayList<>();
List<Date> days = new ArrayList<>();
Calendar tempStart = Calendar.getInstance();
tempStart.setTime(start);
Calendar tempEnd = Calendar.getInstance();
tempEnd.setTime(end);
tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
while (tempStart.before(tempEnd)) {
days.add(tempStart.getTime());
strDayList.add(DateUtil.formatDate(tempStart.getTime()));
tempStart.add(Calendar.DAY_OF_YEAR, 1);
}
return strDayList;
}
// 使用
public static void main(String[] args) {
List<String> allDateList = getBetweenDaysStr(
DateUtil.parse("2024-03-29", DatePattern.NORM_DATE_PATTERN),
DateUtil.parse("2024-04-05", DatePattern.NORM_DATE_PATTERN)
);
System.out.println(allDateList);
//返回: [2024-03-29, 2024-03-30, 2024-03-31, 2024-04-01, 2024-04-02, 2024-04-03, 2024-04-04, 2024-04-05]
}
}