Home  >  Article  >  Web Front-end  >  How to calculate age in javascript

How to calculate age in javascript

青灯夜游
青灯夜游Original
2021-09-16 18:24:1910004browse

Javascript method for calculating age: 1. Get the year, month and day of birth respectively; 2. Get the year, month and day of the current time respectively; 3. Subtract two to get the difference in years, days and months. 4. Calculate the age through the difference between years, months and days.

How to calculate age in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Javascript method of calculating age

function jsGetAge(strBirthday){
  var returnAge;
  // 根据生日计算年龄
  //以下五行是为了获取出生年月日,如果是从身份证上获取需要稍微改变一下
  var strBirthdayArr=strBirthday.split("-");
  var birthYear = strBirthdayArr[0];
  var birthMonth = strBirthdayArr[1];
  var birthDay = strBirthdayArr[2];

  d = new Date();
  var nowYear = d.getFullYear();
  var nowMonth = d.getMonth() + 1;
  var nowDay = d.getDate();

  if(nowYear == birthYear){
    returnAge = 0;//同年 则为0岁
  }
  else{
    var ageDiff = nowYear - birthYear ; //年之差
    if(ageDiff > 0){
      if(nowMonth == birthMonth) {
        var dayDiff = nowDay - birthDay;//日之差
        if(dayDiff < 0)
        {
          returnAge = ageDiff - 1;
        }
        else
        {
          returnAge = ageDiff ;
        }
      }
      else
      {
        var monthDiff = nowMonth - birthMonth;//月之差
        if(monthDiff < 0)
        {
          returnAge = ageDiff - 1;
        }
        else
        {
          returnAge = ageDiff ;
        }
      }
    }
    else
    {
      returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天
    }
  }

  return returnAge;//返回周岁年龄

}

Call the jsGetAge() function, the birthday is 1995-09-15

console.log(jsGetAge("1995-09-15"));

The age is:

26

If the birthday is 1995-09-25

console.log(jsGetAge("1995-09-25"));

, then the age is:

25

[Recommended learning: javascript advanced tutorial

The above is the detailed content of How to calculate age in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn