日期:2014-05-16  浏览次数:20411 次

关于根据出生日期计算年龄的问题(js,java)
js中计算年龄
/**
* 将生日转换成年龄
*/
function birthDayToAge(){
var aDate=new Date();
var thisYear = aDate.getFullYear();
var thisMonth = aDate.getMonth()+1;
var thisDay = aDate.getDate();
var currentDate = thisYear+"-"+thisMonth+"-"+thisDay;
var oTable = document.getElementById('familyMember');
var message = $("#message").html();
if(message != null && message != "" ){
return null;
}
for(i=1;i<oTable.rows.length;i++){
    var cell = oTable.rows[i].cells[3].innerHTML;
    if(cell!="" && cell != null){
    age = daysBetween(currentDate,cell.trim());
    oTable.rows[i].cells[3].innerHTML = age;
    }else{
    oTable.rows[i].cells[3].innerHTML = "";
    }
}
}

/** 计算两个日期间的年龄  */
function daysBetween(DateOne,DateTwo){  
    var OneMonth = DateOne.substring(5,DateOne.lastIndexOf ('-')); 
    var OneDay = DateOne.substring(DateOne.length,DateOne.lastIndexOf ('-')+1); 
    var OneYear = DateOne.substring(0,DateOne.indexOf ('-')); 
 
    var TwoMonth = DateTwo.substring(5,DateTwo.lastIndexOf ('-')); 
    var TwoDay = DateTwo.substring(DateTwo.length,DateTwo.lastIndexOf ('-')+1); 
    var TwoYear = DateTwo.substring(0,DateTwo.indexOf ('-')); 
 
    var cha=((Date.parse(OneMonth+'/'+OneDay+'/'+OneYear)- Date.parse(TwoMonth+'/'+TwoDay+'/'+TwoYear))/86400000/365);  
   var age = Math.abs(cha)+1+"";
    return age.split(".")[0];
}


java中计算年龄
/** 计算年龄 */
public  String getAge(Date birthDay) throws Exception {
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthDay)) {
            throw new IllegalArgumentException(
                "The birthDay is before Now.It's unbelievable!");
        }

        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH)+1;
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
       
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                //monthNow==monthBirth
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                }