Sometimes we need to generate data over a period of time.
If you run data day by day, congratulations, you understand~~ The following is a tool class for traversing dates. When calling, just pass the start time and end time.
/**
* 获取时间段内的时间方法
* @param startTime
* @param endTime
* @return
*/
public static List<String> dateSplit(String startTime, String endTime) {
// 日期格式化
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
List<String> timeList = new ArrayList<>();
try {
// 起始日期
Date d1 = sdf.parse(startTime);
// 结束日期
Date d2 = sdf.parse(endTime);
Date tmp = d1;
calendar.setTime(d1);
while (tmp.getTime() < d2.getTime()) {
timeList.add(sdf.format(calendar.getTime()));
tmp = calendar.getTime();
// 天数加上1
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
} catch (ParseException e) {
e.printStackTrace();
}
return timeList;
}
Let's test it next
public static void main(String[] args) {
List<String> timeList = dateSplit("2023-02-20", "2023-02-28");
for (String time : timeList) {
// 此处可以调用业务
System.out.println(time);
}
}
Let’s take a look at the results
Okay, take it and use it, friends~~