javascript - 年龄计算
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4076321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript - Age calculation
提问by user160820
Having 2 javascript Dates,
有 2 个 javascript 日期,
first is birthdate and second is a date to calculate age from that date.
第一个是生日,第二个是从该日期计算年龄的日期。
What should be the best way to do this.
什么应该是最好的方法来做到这一点。
回答by Matt
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;
}
Example:
例子:
var age = calculateAge("02/24/1991", "02/24/2010"); // Format: MM/DD/YYYY
回答by Mic
Here is a way:
这是一种方法:
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)) );
Be careful with the month. Javascript counts them from 0.1978, 10, 3
means the November 3th, 1978
小心月份。Javascript 从 0 开始计数。1978, 10, 3
表示 1978 年 11 月 3 日
回答by Dinesh Rabara
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
Date (MM/DD/YYYY):Calculate Age
日期 (MM/DD/YYYY):计算年龄
年龄:7岁1个月15天。回答by vibs2006
Here is one example using moment.jslibrary which is very common now days. Just adding this answer in many of other answers.
这是一个使用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>
回答by Frédéric Hamidi
Convert the date to milliseconds since the epoch using getTime(), then subtract the values and convert the result back to years:
使用getTime()将日期转换为自纪元以来的毫秒数,然后减去这些值并将结果转换回年份:
const MS_PER_YEAR = 1000 * 60 * 60 * 24 * 365.2425;
var years = Math.floor((dateNow.getTime() - dateThen.getTime()) / MS_PER_YEARS);
回答by Coin_op
The best way would probably be to convert the date into a timestamp, probably using parse()
if the date is a string. Then simply subtracting the numbers and converting the new number back to a date using new Date(milliseconds)
最好的方法可能是将日期转换为时间戳,parse()
如果日期是字符串,则可能使用。然后简单地减去数字并将新数字转换回日期使用new Date(milliseconds)
This might not be too accurate for dates before the 1/1/1970 though, so the alternative method of subtracting days, months, etc... separately would be more suitable.
不过,对于 1/1/1970 之前的日期,这可能不太准确,因此分别减去天数、月数等的替代方法会更合适。
回答by Gabriele Petrioli
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 );
回答by Pascal Qyy
If you are in an huge Javascript project, you maybe [use|need to use] a framework...
如果你在一个巨大的 Javascript 项目中,你可能[使用|需要使用]一个框架......
With Mootools More, you have a Date Typewith a diff methodand a timeDiff methodthat can fit to your needs.
使用Mootools More,您有一个日期类型,它带有一个 diff 方法和一个timeDiff 方法,可以满足您的需要。
It even provide localisation!
它甚至提供本地化!
回答by Texura
I've modified Mic's response to allow for today being the user's birthday. The difference is the date you're checking the age of should be set to midnight of that day and/or the current date should be set to 23:59:59. An example would be to see if the user is 18 today, this will return 18.
我已经修改了 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)));
回答by Mati Cassanelli
A simple way to do this is using moment.js.
一个简单的方法是使用moment.js。
We have two dates, the birth date (birthDate) and the other date used to calculate age from (specificDate). You can avoid this parameter and get the current age.
我们有两个日期,出生日期 (birthDate) 和用于计算年龄的另一个日期 (specificDate)。您可以避免此参数并获取当前年龄。
moment(specificDate).diff(moment(birthDate), 'years');
Hope it helps you!
希望对你有帮助!