javascript 在javascript中检查年龄是否不小于13岁
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14231381/
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
To check if age is not less than 13 years in javascript
提问by ap.singh
Can anyone please guide me through javascript function, which will fetch me year difference between current date and date entered by user
任何人都可以指导我完成 javascript 函数,它将获取当前日期和用户输入的日期之间的年差
I have tried this, but it doesnot keep in count leap years
我试过这个,但它不计算闰年
var yearOld=2000
var dateOld=11
var mnthOld=1;
var currendDate=new Date(); // 9 - jan - 2013
var oldDate=new Date(yearOld,mnthOld-1,dateOld);
var timeDiff =currendDate-oldDate ;
var diffDays = timeDiff / (1000 * 3600 * 24 * 365);
Result is coming 13.00789 something where it should come less than 13
结果是 13.00789,它应该小于 13
Any help will be appreciated
任何帮助将不胜感激
回答by Dawid Sajdak
function getAge(birthDateString) {
var today = new Date();
var birthDate = new Date(birthDateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
if(getAge("27/06/1989") >= 18) {
alert("You have 18 or more years old!");
}
回答by Mahbub
If you have good amount of Date related operations, consider using MomentJS http://momentjs.com/. Check the first two examples there and i guess they fit your question.
如果您有大量与日期相关的操作,请考虑使用 MomentJS http://momentjs.com/。检查那里的前两个示例,我想它们适合您的问题。
回答by Walter Brand
http://www.datejs.com/is a useful library for all kinds of calculations with dates
http://www.datejs.com/是一个有用的库,用于各种日期计算
回答by Satya
Use
利用
// millisecs * secs * mins * hrs * days (inclu. leap)
msecsInYear = 1000 * 60 * 60 * 24 * 365.25;
Note: Statically not correct, but is mathematically correct!
Will cover leap year cases.
注意:静态上不正确,但在数学上是正确的!
将涵盖闰年情况。
回答by pysoserious
// 1. Get current date
// 2. Add 13 to the year in DOB.
// 3. check if current year is less than dob-year. If not person is older than 13 years
// 4. And so on check for month and date
var date_of_birth = '2015-12-26' // example DOB
var is_13 = true; // flag for 13
dob = date_of_birth.trim(); // trim spaces form DOB
y = parseInt(dob.substr(0,4)); // fetch year using substr() from DOB
m = parseInt(dob.substr(5,2)); // fetch month using substr() from DOB
d = parseInt(dob.substr(8,2)); // fetch date using substr() from DOB
// the above logic can change depending on the format of the input DOB
var r = new Date(); // Gets current Date
if(r.getFullYear() <= (parseInt(y) + 13)){
if((r.getMonth()+1) <= m){
if(r.getDate() < d){
is_13 = false;
console.log('less than 13');
}}}