javascript - 年龄计算

时间:2010-11-02 09:25:25

标签: javascript

有2个javascript日期,

首先是生日 第二个是从该日期开始计算年龄的日期。

这应该是最好的方法。

13 个答案:

答案 0 :(得分:28)

function calculateAge (birthDate, otherDate) {
    birthDate = new Date(birthDate);
    otherDate = new Date(otherDate);

    var years = (otherDate.getFullYear() - birthDate.getFullYear());

    if (otherDate.getMonth() < birthDate.getMonth() || 
        otherDate.getMonth() == birthDate.getMonth() && otherDate.getDate() < birthDate.getDate()) {
        years--;
    }

    return years;
}

示例:

var age = calculateAge("02/24/1991", "02/24/2010"); // Format: MM/DD/YYYY

答案 1 :(得分:13)

这是一种方式:

function getAge(d1, d2){
    d2 = d2 || new Date();
    var diff = d2.getTime() - d1.getTime();
    return Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
}
console.log( getAge(new Date(1978, 10, 3)) );

小心月份。 Javascript从0开始计算。
1978, 10, 3表示1978年11月3日

答案 2 :(得分:5)

function getAge(dateString) {
  var now = new Date();
  var today = new Date(now.getYear(),now.getMonth(),now.getDate());

  var yearNow = now.getYear();
  var monthNow = now.getMonth();
  var dateNow = now.getDate();

  var dob = new Date(dateString.substring(6,10),
                     dateString.substring(0,2)-1,                   
                     dateString.substring(3,5)                  
                     );

  var yearDob = dob.getYear();
  var monthDob = dob.getMonth();
  var dateDob = dob.getDate();
  var age = {};
  var ageString = "";
  var yearString = "";
  var monthString = "";
  var dayString = "";


  yearAge = yearNow - yearDob;

  if (monthNow >= monthDob)
    var monthAge = monthNow - monthDob;
  else {
    yearAge--;
    var monthAge = 12 + monthNow -monthDob;
  }

  if (dateNow >= dateDob)
    var dateAge = dateNow - dateDob;
  else {
    monthAge--;
    var dateAge = 31 + dateNow - dateDob;

    if (monthAge < 0) {
      monthAge = 11;
      yearAge--;
    }
  }

  age = {
      years: yearAge,
      months: monthAge,
      days: dateAge
      };

  if ( age.years > 1 ) yearString = " years";
  else yearString = " year";
  if ( age.months> 1 ) monthString = " months";
  else monthString = " month";
  if ( age.days > 1 ) dayString = " days";
  else dayString = " day";


  if ( (age.years > 0) && (age.months > 0) && (age.days > 0) )
    ageString = age.years + yearString + ", " + age.months + monthString + ", and " + age.days + dayString + " old.";
  else if ( (age.years == 0) && (age.months == 0) && (age.days > 0) )
    ageString = "Only " + age.days + dayString + " old!";
  else if ( (age.years > 0) && (age.months == 0) && (age.days == 0) )
    ageString = age.years + yearString + " old. Happy Birthday!!";
  else if ( (age.years > 0) && (age.months > 0) && (age.days == 0) )
    ageString = age.years + yearString + " and " + age.months + monthString + " old.";
  else if ( (age.years == 0) && (age.months > 0) && (age.days > 0) )
    ageString = age.months + monthString + " and " + age.days + dayString + " old.";
  else if ( (age.years > 0) && (age.months == 0) && (age.days > 0) )
    ageString = age.years + yearString + " and " + age.days + dayString + " old.";
  else if ( (age.years == 0) && (age.months > 0) && (age.days == 0) )
    ageString = age.months + monthString + " old.";
  else ageString = "Oops! Could not calculate age!";

  return ageString;
}

// A bit of jQuery to call the getAge() function and update the page...
$(document).ready(function() {
  $("#submitDate").click(function(e) {
    e.preventDefault();

    $("#age").html(getAge($("input#date").val()));

  });
});

and HTML IS

日期(MM / DD / YYYY):计算年龄

年龄:7岁,1个月和15天。

答案 3 :(得分:2)

使用getTime()将日期转换为自纪元以来的毫秒数,然后减去这些值并将结果转换回年份:

const MS_PER_YEAR = 1000 * 60 * 60 * 24 * 365.2425;
var years = Math.floor((dateNow.getTime() - dateThen.getTime()) / MS_PER_YEARS);

答案 4 :(得分:1)

最好的方法可能是将日期转换为时间戳,如果日期是字符串,则可能使用parse()。然后简单地使用new Date(milliseconds)

减去数字并将新数字转换回日期

对于1970年1月1日之前的日期,这可能不太准确,所以另外减去天,月等等的替代方法会更合适。

答案 5 :(得分:1)

var birth = new Date('07/11/2003');
var check = new Date();

var milliDay = 1000 * 60 * 60 * 24; // a day in milliseconds;


var ageInDays = (check - birth) / milliDay;

var ageInYears =  Math.floor(ageInDays / 365 );

示例http://www.jsfiddle.net/gaby/XDKa3/1/

答案 6 :(得分:1)

如果您在一个庞大的Javascript项目中,您可能[使用|需要使用]框架......

使用Mootools More,您有一个Date Type diff methodtimeDiff method,可以满足您的需求。

它甚至provide localisation

答案 7 :(得分:1)

一种简单的方法是使用moment.js

我们有两个日期,一个是出生日期(birthDate),另一个是用来从(specificDate)计算年龄的日期。您可以避免使用此参数并获取当前年龄。

moment(specificDate).diff(moment(birthDate), 'years');

希望对您有帮助!

答案 8 :(得分:0)

我修改了Mic的回复以允许今天成为用户的生日。不同之处在于您检查年龄的日期应设置为当天的午夜和/或当前日期应设置为23:59:59。一个例子是看今天用户是18,这将返回18。

function getAge(d1){
    var now = new Date();
    var d2 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
    var diff = d2.getTime() - d1.getTime();
    return Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
}
console.log(getAge(new Date(1992, 10, 17, 0, 0, 0)));

答案 9 :(得分:0)

function getAge(dateOfBirth, tillDate) {
    var dob = new Date(dateOfBirth);
    var endDt = new Date(tillDate) || new Date();
    return new Date(endDt.getTime() - dob.getTime()).getUTCFullYear() - 1970;
}

示例: console.log(getAge('1/1/2000', '1/1/2016')); // Format: MM/DD/YYYY

答案 10 :(得分:0)

按当年计算年龄

calculateExp(birthDate) {
    birthDate = new Date(birthDate);
    var now = new Date();
    otherDate = new Date(now.getFullYear(),now.getMonth(),now.getDate());
    var years = (otherDate.getFullYear() - birthDate.getFullYear() );


    if (otherDate.getMonth() < birthDate.getMonth() || otherDate.getMonth() == birthDate.getMonth() && otherDate.getDate() < birthDate.getDate()) {
        years--;
    }

    return years;
}

答案 11 :(得分:0)

这里是使用 moment.js 库的一个例子,这在当今很普遍。只需将此答案添加到其他许多答案中即可。

var banner = $("#banner-message")
var button = $("button")

// handle click and add class
button.on("click", function(){
  var inputValue = $("#txtInput").val();
  var age = parseInt(moment().diff(inputValue,'years',true));
  
$("#spantext").html(age + ' years.');
  
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div id="banner-message">
  <p>Enter Date: <input type='text' id='txtInput' value='1981-12-25' /></p>
  <label>Age is : </label><span id='spantext'></span> <br/>
  <p><button>Calculate Age</button></p>
</div>

答案 12 :(得分:0)

此句柄还适用于leap年:

const getAgeFromBirthDate = (year, month, day) => {
   const date = new Date();
   date.setFullYear(date.getFullYear() - year);
   date.setMonth(date.getMonth() - month);
   //date.setDate(date.getDate() - day);
   return date;
};

console.log( getAgeFromBirthDate(1994, 07, 19).getFullYear() );

相关问题