java根据日期获取月龄,按照减法原理,先day相减,不够向month借;然后month相减,不够向year借;最后year相减。

/**
* 函数名: getMonthNum
* 功能: 相差月数
* 参数: @param start 开始时间
* 参数: @param end 结束时间
* 返回值: int
*/
public static int getMonthNum(Date start,Date end)
{
Calendar birthday =Calendar.getInstance();
birthday.setTime(start);
Calendar now = Calendar.getInstance();
now.setTime(end);
int day = now.get(Calendar.DAY_OF_MONTH) - birthday.get(Calendar.DAY_OF_MONTH);
int month = now.get(Calendar.MONTH) - birthday.get(Calendar.MONTH);
int year = now.get(Calendar.YEAR) - birthday.get(Calendar.YEAR);
//按照减法原理,先day相减,不够向month借;然后month相减,不够向year借;最后year相减。
if(day<0)
{
month -= 1;
now.add(Calendar.MONTH, -1);//得到上一个月,用来得到上个月的天数。
day = day + now.getActualMaximum(Calendar.DAY_OF_MONTH);
}
if(month<0)
{
month = (month+12)%12;
year--;
}
if(year>0)
{
month=year*12+month;
}
//System.out.println("******"+month);
return month;
}

posted @ 2018-04-12 17:13  魔杰Lee  阅读(443)  评论(0编辑  收藏  举报