java:根据日期期间获取连续日期
1 前言:
给定起始、终止的日期,通过java实现获取连续的日期字符串,可通过c.add(Calendar.DATE, 1)循环获取结果。
2 使用:
public static List<String> getDatas(String startDay, String endDay){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
List<String> locals = new ArrayList<>();
if(startDay == null || endDay == null){
throw new RuntimeException("error");
}
try {
Date startD = sdf.parse(startDay);
Date endD = sdf.parse(endDay);
if(!startD.before(endD)){
throw new RuntimeException("startDay must before endDay");
}
Date startClone = (Date) startD.clone();
while(!startClone.after(endD)){
locals.add(sdf.format(startClone));
Calendar c = Calendar.getInstance();
c.setTime(startClone);
c.add(Calendar.DATE, 1);
startClone = c.getTime();
}
} catch (Throwable e) {
throw new RuntimeException(e);
}
return locals;
}
测试代码:
List<String> datas = getDatas("2023-02-26", "2023-03-02");
datas.forEach(System.out::println);
执行结果如下:
2023-02-26
2023-02-27
2023-02-28
2023-03-01
2023-03-02