java 获取两个日期相差的月份
前两天要用到获取两个时间之间的月份差,今天总结下。
/**
* 获取连个日期之间相差的月份
* @param startDate
* @param endDate
* @return
* @throws ParseException
*/
private static List getMonth(String startDate, String endDate) throws ParseException {
List 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;
}
当前月份向前或向后推。
/**
* 计算前几个月/后几个月
* @param date
* @param flag
* @return
* @throws ParseException
*/
private static List getMonth(String date, boolean flag, int num) throws ParseException{
List 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;
}
方法调用
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();
}
}
输出结果
非常好用 希望大家能够喜欢
原文链接:https://blog.csdn.net/weixin_39823527/article/details/103007523