js根据出生日期计算年龄(附java计算年龄代码)

发布时间:2019-07-23编辑:脚本学堂
分享二段脚本,js计算年龄与java计算年龄的代码,将生日转换成年龄,计算两个日期间的年龄,需要的朋友参考下。

例1,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];
}

例2,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--;
    }
} else {
    //monthNow>monthBirth
    age--;
}
}
return age +"";
}