java获取⼀个时间段内的所有年份⽉份天代码⽰例:
/**
* 枚举类
*/
public enum DateUnit {
YEAR("year"),
MONTH("month"),
DAY("day");
private String unit;
DateUnit(String unit) {
this.unit = unit;
}
public String getUnit() {
return this.unit;
}
}java时间日期格式转换
/**
* 获取两个⽇期字符串之间的所有年份/⽉份/天(左闭右闭)
*
* @param startDateStr  yyyyMMdd
* @param endDateStr    yyyyMMdd
* @param dateUnit
* @return
*/
public static List<String> getDateStrBetween(String startDateStr, String endDateStr, DateUnit dateUnit) {
List<String> result = new ArrayList<>();
SimpleDateFormat sdf;
Calendar start = Instance();
Calendar end = Instance();
try {
sdf = new SimpleDateFormat("yyyyMMdd");
start.setTime(sdf.parse(startDateStr));
end.setTime(sdf.parse(endDateStr));
//            end.add(Calendar.DAY_OF_MONTH,-1); // end往前减1天,处理20210101这种情况(实现左闭右开)
} catch (ParseException e) {
e.printStackTrace();
}
Calendar curr = start;
switch (dateUnit) {
case YEAR:
sdf = new SimpleDateFormat("yyyy");
while (curr.before(end)) {
result.add(sdf.Time()));
curr.add(Calendar.YEAR, 1);
}
break;
case MONTH:
sdf = new SimpleDateFormat("yyyyMM");
while (curr.before(end)) {
result.add(sdf.Time()));
curr.add(Calendar.MONTH, 1);
}
break;
case DAY:
sdf = new SimpleDateFormat("yyyyMMdd");
sdf = new SimpleDateFormat("yyyyMMdd");
while (curr.before(end)) {
result.add(sdf.Time()));
curr.add(Calendar.DAY_OF_MONTH, 1);
}
break;
default:
sdf = new SimpleDateFormat("yyyy");
while (curr.before(end)) {
result.add(sdf.Time()));
curr.add(Calendar.YEAR, 1);
}
break;
}
// 最后要加上 endDateStr 所属的年份/⽉份/天(保证不漏)        result.add(sdf.Time()));
return result.stream().distinct().List());    }

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。