java计算两个日期之间相隔的月份(向下取整)
最近需求里面有个需要计算两个日期之间相隔的月份,写起来还挺繁琐,需要将各种情况都要考虑到,写了一个作为以后自己的工具吧。
1 //获取哪一天 2 public static int getDay(Date date) { 3 Calendar calendar = Calendar.getInstance(); 4 calendar.setTime(date); 5 return calendar.get(Calendar.DATE); 6 } 7 8 /** 9 * 返回日期的月份,1-12,即yyyy-MM-dd中的MM 10 * 11 * @param date 12 * @return 13 */ 14 public static int getMonth(Date date) { 15 Calendar calendar = Calendar.getInstance(); 16 calendar.setTime(date); 17 return calendar.get(Calendar.MONTH) + 1; 18 } 19 20 /** 21 * 返回日期的年,即yyyy-MM-dd中的yyyy 22 * 23 * @param date 24 * Date 25 * @return int 26 */ 27 public static int getYear(Date date) { 28 Calendar calendar = Calendar.getInstance(); 29 calendar.setTime(date); 30 return calendar.get(Calendar.YEAR); 31 } 32 public static int calDiffMonth(String startDate,String endDate) { 33 int result=0; 34 try { 35 SimpleDateFormat sfd=new SimpleDateFormat("yyyyMMdd"); 36 Date start = sfd.parse(startDate); 37 Date end = sfd.parse(endDate); 38 int startYear=getYear(start); 39 int startMonth=getMonth(start); 40 int startDay=getDay(start); 41 int endYear=getYear(end); 42 int endMonth=getMonth(end); 43 int endDay=getDay(end); 44 45 Calendar calendar2= Calendar.getInstance(); 46 calendar2.setTime(start); 47 int maxDay = calendar2.getActualMaximum(Calendar.DAY_OF_MONTH);//获取起始日期所在月的最后一天 48 Calendar calendar3 = Calendar.getInstance(); 49 calendar3.setTime(end); 50 int maxEndDay = calendar3.getActualMaximum(Calendar.DAY_OF_MONTH);//获取结束日期所在月的最后一天 51 if(startDay == maxDay){//起始日期是在月末 52 if(maxEndDay==endDay){ 53 result=(endYear-startYear)*12+endMonth-startMonth; 54 }else { 55 result=(endYear-startYear)*12+endMonth-startMonth-1; 56 } 57 }else if(endDay==maxEndDay){//结束日期是在月末 58 result=(endYear-startYear)*12+endMonth-startMonth; 59 }else { 60 if (endDay >= startDay) { 61 result=(endYear-startYear)*12+endMonth-startMonth; 62 }else { 63 result=(endYear-startYear)*12+endMonth-startMonth-1; 64 } 65 } 66 } catch (Exception e) { 67 e.printStackTrace(); 68 } 69 return result; 70 } 71 72 73 public static void main(String[] args) { 74 int i = calDiffMonth("20171030", "20180228"); 75 System.out.println(i); 76 }
越努力越幸运