获取两个日期之间的日期(年/月/日),包括开始结束日期
程序员文章站
2022-06-07 12:12:34
...
/**
* 获取两个日期之间的日期(年/月/日),包括开始结束日期
* @param start 开始日期
* @param end 结束日期
* @param choose 0:取年份,1取月份,2取天
* @return 日期集合
*/
public List<String> getBetweenDates(Date start, Date end,int choose) {
SimpleDateFormat sdf = null;
int filid = 0;
String endTime = "";
if(choose == 0) {
sdf = new SimpleDateFormat("yyyy");
filid = Calendar.YEAR;
endTime = sdf.format(end);
}else if(choose == 1) {
sdf = new SimpleDateFormat("MM");
filid = Calendar.MONTH;
endTime = sdf.format(end);
}else {
sdf = new SimpleDateFormat("dd");
filid = Calendar.DAY_OF_YEAR;
endTime = sdf.format(end);
}
List<String> result = new ArrayList<String>();
Calendar tempStart = Calendar.getInstance();
tempStart.setTime(start);
tempStart.add(filid, 1);
Calendar tempEnd = Calendar.getInstance();
tempEnd.setTime(end);
result.add(sdf.format(start));
Boolean state = false;
while (tempStart.before(tempEnd)) {
result.add(sdf.format(tempStart.getTime()));
if(sdf.format(tempStart.getTime()).equals(endTime)) {
state = true;
}
tempStart.add(filid, 1);
}
if(!state) {
result.add(endTime);
}
return result;
}
上一篇: java8新特性之Optional