java计算两个日期之间相隔的月份(向下取整)

时间:2023-03-08 16:02:44

最近需求里面有个需要计算两个日期之间相隔的月份,写起来还挺繁琐,需要将各种情况都要考虑到,写了一个作为以后自己的工具吧。

 //获取哪一天
public static int getDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DATE);
} /**
* 返回日期的月份,1-12,即yyyy-MM-dd中的MM
*
* @param date
* @return
*/
public static int getMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MONTH) + 1;
} /**
* 返回日期的年,即yyyy-MM-dd中的yyyy
*
* @param date
* Date
* @return int
*/
public static int getYear(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.YEAR);
}
public static int calDiffMonth(String startDate,String endDate) {
int result=0;
try {
SimpleDateFormat sfd=new SimpleDateFormat("yyyyMMdd");
Date start = sfd.parse(startDate);
Date end = sfd.parse(endDate);
int startYear=getYear(start);
int startMonth=getMonth(start);
int startDay=getDay(start);
int endYear=getYear(end);
int endMonth=getMonth(end);
int endDay=getDay(end); Calendar calendar2= Calendar.getInstance();
calendar2.setTime(start);
int maxDay = calendar2.getActualMaximum(Calendar.DAY_OF_MONTH);//获取起始日期所在月的最后一天
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(end);
int maxEndDay = calendar3.getActualMaximum(Calendar.DAY_OF_MONTH);//获取结束日期所在月的最后一天
if(startDay == maxDay){//起始日期是在月末
if(maxEndDay==endDay){
result=(endYear-startYear)*12+endMonth-startMonth;
}else {
result=(endYear-startYear)*12+endMonth-startMonth-1;
}
}else if(endDay==maxEndDay){//结束日期是在月末
result=(endYear-startYear)*12+endMonth-startMonth;
}else {
if (endDay >= startDay) {
result=(endYear-startYear)*12+endMonth-startMonth;
}else {
result=(endYear-startYear)*12+endMonth-startMonth-1;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
} public static void main(String[] args) {
int i = calDiffMonth("20171030", "20180228");
System.out.println(i);
}