输入开始日期和结束日期,输出中间的日期和月份。如2017-01-01和2018-03-05,
输入日期中间日期为:
2017-01-01,2017-01-02,2017-01-03......2018-03-05
输出中间月份为:
2017-01,2017-02,2017-03......2018-03
计算中间日期代码:
/**
* 根据开始时间和结束时间返回时间段内的时间集合
*
* @param start
* @param end
* @return List
*/
public static List<Date> getDatesBetweenTwoDate(String start, String end) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date beginDate = sdf.parse(start);
Date endDate = sdf.parse(end);
if (beginDate.compareTo(endDate) > 0) {
Date tmp = endDate;
endDate = beginDate;
beginDate = tmp;
}
List<Date> lDate = new ArrayList<Date>();
lDate.add(beginDate);// 把开始时间加入集合
Calendar cal = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
cal.setTime(beginDate);
boolean bContinue = true;
while (bContinue) {
// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
cal.add(Calendar.DAY_OF_MONTH, 1);
// 测试此日期是否在指定日期之后
if (endDate.after(cal.getTime())) {
lDate.add(cal.getTime());
} else {
break;
}
}
lDate.add(endDate);// 把结束时间加入集合
return lDate;
}
计算中间月份代码:
/**
* 根据开始时间和结束时间返回时间段内的月份集合
*
* @param start
* @param end
* @return List
*/
public static List<String> getMonthBetweenTwoDate(String start, String end) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date beginDate = sdf.parse(start);
Date endDate = sdf.parse(end);
if (beginDate.compareTo(endDate) > 0) {
Date tmp = endDate;
endDate = beginDate;
beginDate = tmp;
}
List<String> lDate = new ArrayList<String>();
Calendar calendar = Calendar.getInstance();
calendar.setTime(beginDate);
int startYear = calendar.get(Calendar.YEAR);
int startMonth = calendar.get(Calendar.MONTH);
calendar.setTime(endDate);
int endYear = calendar.get(Calendar.YEAR);
int endMonth = calendar.get(Calendar.MONTH);
for (int i = startYear; i <= endYear; i++) {
String date = "";
if (startYear == endYear) {
for (int j = startMonth; j <= endMonth; j++) {
if (j < 9) {
date = i+"-0"+ (j+1);
} else {
date = i+"-"+ (j+1);
}
lDate.add(date);
}
} else {
if (i == startYear){
for (int j = startMonth; j < 12; j++) {
if (j < 9) {
date = i+"-0"+ (j+1);
} else {
date = i+"-"+ (j+1);
}
lDate.add(date);
}
} else if (i == endYear) {
for (int j = 0; j <= endMonth; j++) {
if (j < 9) {
date = i+"-0"+ (j+1);
} else {
date = i+"-"+ (j+1);
}
lDate.add(date);
}
} else {
for (int j = 0; j < 12; j++) {
if (j < 9) {
date = i+"-0"+ (j+1);
} else {
date = i+"-"+ (j+1);
}
lDate.add(date);
}
}
}
}
return lDate;
}
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String start = "2018-01-03";
String end = "2018-04-16";
List<Date> listDate = getDatesBetweenTwoDate(start, end);
for (int i = 0; i < listDate.size(); i++) {
System.out.println(sdf.format(listDate.get(i)));
}
List<String> listMonth = getMonthBetweenTwoDate(start, end);
for (String s : listMonth) {
System.out.println(s);
}
}