/**
* 获取两个月份之间的所有月份(含跨年)
*/
public static List getMonthBetween(String minDate, String maxDate) throws ParseException {
ArrayList result = new ArrayList();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");// 格式化为年月
Calendar min = Calendar.getInstance();
Calendar max = Calendar.getInstance();
min.setTime(sdf.parse(minDate));
min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
max.setTime(sdf.parse(maxDate));
max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
Calendar curr = min;
while (curr.before(max)) {
result.add(sdf.format(curr.getTime()));
curr.add(Calendar.MONTH, 1);
}
// 实现排序方法
Collections.sort(result, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
String str1 = (String) o1;
String str2 = (String) o2;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
Date date1 = null;
Date date2 = null;
try {
date1 = format.parse(str1);
date2 = format.parse(str2);
} catch (ParseException e) {
e.printStackTrace();
}
if (date2.compareTo(date1) < 0) {
return -1;
}
return 1;
}
});
return result;
}
计算当前月天数
/**
* 计算当前月有多少天
*
* @return
*/
public int getDays(int year, int month) {
int days = 0;
if (month != 2) {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
}
} else {
// 闰年
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
days = 29;
else
days = 28;
}
System.out.println("当月有" + days + "天!");
return days;
}
计算年份之间的所有年份
/**
* 补全年份
* @param startYear
* @param endYear
* @return
*/
public List<String> getYear(String startYear, String endYear){
List<String> year = new ArrayList();
SimpleDateFormat format = new SimpleDateFormat("yyyy");
try{
Date dBegin = format.parse(startYear);
Date dEnd = format.parse(endYear);
year.add(format.format(dBegin));
Calendar calBegin = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
calBegin.setTime(dBegin);
Calendar calEnd = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
calEnd.setTime(dEnd);
// 测试此日期是否在指定日期之后
while (dEnd.after(calBegin.getTime())) {
// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
calBegin.add(Calendar.YEAR, 1);
year.add(format.format(calBegin.getTime()));
}
}catch(Exception e){
return year;
}
return year;
}