Java获取两个日期之间的年月日, 存到数组中
public class TestMain {
//测试方法
public static void main(String[] args) {
System.out.println(getTimeList("2018", "2020"));
System.out.println(getTimeList("2018-10", "2020-02"));
System.out.println(getTimeList("2018-10-24", "2018-11-12"));
}
// 传入两个日期,输出间隔的 年月日
public static List<String> getTimeList(String startDate, String endxDate){
SimpleDateFormat sdf ;
int calendarType;
switch (startDate.length()){
case 10:
sdf = new SimpleDateFormat("yyyy-MM-dd");
calendarType = Calendar.DATE;
break;
case 7:
sdf = new SimpleDateFormat("yyyy-MM");
calendarType = Calendar.MONTH;
break;
case 4:
sdf = new SimpleDateFormat("yyyy");
calendarType = Calendar.YEAR;
break;
default:
return null;
}
// 存放 相隔的日期
List<String> result = new ArrayList<>();
Calendar min = Calendar.getInstance();
Calendar max = Calendar.getInstance();
try {
min.setTime(sdf.parse(startDate));
min.add(calendarType, 0);
max.setTime(sdf.parse(endxDate));
max.add(calendarType, 1);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar curr = min;
while (curr.before(max)) {
result.add(sdf.format(min.getTime()));
curr.add(calendarType, 1);
}
return result;
}
}
结果
[2018, 2019, 2020]
[2018-10, 2018-11, 2018-12, 2019-01, 2019-02, 2019-03, 2019-04, 2019-05, 2019-06, 2019-07, 2019-08, 2019-09, 2019-10, 2019-11, 2019-12, 2020-01, 2020-02]
[2018-10-24, 2018-10-25, 2018-10-26, 2018-10-27, 2018-10-28, 2018-10-29, 2018-10-30, 2018-10-31, 2018-11-01, 2018-11-02, 2018-11-03, 2018-11-04, 2018-11-05, 2018-11-06, 2018-11-07, 2018-11-08, 2018-11-09, 2018-11-10, 2018-11-11, 2018-11-12]