一、获取指定时间区间的字符串
1.1 指定开始结束时间
/**
* 获取连个日期之间相差的月份
* @param startDate
* @param endDate
* @return
* @throws ParseException
*/
private static List<String> getMonth(String startDate, String endDate) throws ParseException {
List<String> list = new ArrayList();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(sdf.parse(startDate));
c2.setTime(sdf.parse(endDate));
int year = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
int month = c2.get(Calendar.MONTH)+year*12 - c1.get(Calendar.MONTH);
for(int i = 0;i<=month;i++){
c1.setTime(sdf.parse(startDate));
c1.add(c1.MONTH, i);
list.add(sdf.format(c1.getTime()));
}
return list;
}
1.2 当前月份向前或向后推
/**
* 计算前几个月/后几个月
* @param date
* @param flag
* @return
* @throws ParseException
*/
private static List<String> getMonth(String date, boolean flag, int num) throws ParseException{
List<String> list = new ArrayList();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(date));
for(int i = 0;i<num;i++){
c.setTime(sdf.parse(date));
if(flag){
c.add(c.MONTH, i);
}else{
c.add(c.MONTH, i+1-num);
}
list.add(sdf.format(c.getTime()));
}
return list;
}
1.3 方法调用
public static void main(String[] args) {
try {
List list = getMonth("2018-11","2019-10");
System.out.println(list);
List list1 = getMonth("2020-01",true,3);
System.out.println(list1);
} catch (ParseException e) {
e.printStackTrace();
}
}
效果