得到兩個日期相差的月數
阿新 • • 發佈:2018-12-18
public static int monthDiffs(Date endDate,Date startDate ){ Calendar end = Calendar.getInstance(); Calendar start = Calendar.getInstance(); end.setTime(endDate); start.setTime(startDate); //相差的月數 int month = (end.get(Calendar.MONTH) + ( (end.get(Calendar.YEAR) - start.get(Calendar.YEAR))*12 ) - start.get(Calendar.MONTH)); //int month = DateUtils.dateDiff('M', end, start);//相差的月數 int startDays = DateUtils.getDayOfMonth(startDate);//專案開始日期的相應月份共有多少天 int endDays = DateUtils.getDayOfMonth(endDate);//專案結束日期的相應月份共有多少天 if(startDays== start.get(Calendar.DAY_OF_MONTH)){//開始日期是否是月末的最後一天 if(endDays == end.get(Calendar.DAY_OF_MONTH)){//結束日期月末最後一天 month++; }else{ if(end.get(Calendar.DAY_OF_MONTH)>start.get(Calendar.DAY_OF_MONTH)){//結束日期當月天數 > 開始日期單月天數 month++; } } }else{ if(endDays==end.get(Calendar.DAY_OF_MONTH)){//結束日期月末最後一天 month++; }else{ if(end.get(Calendar.DAY_OF_MONTH)>start.get(Calendar.DAY_OF_MONTH)){ month++; } } } return month; }