5

谁能指导我通过javascript函数,它将获取当前日期和用户输入的日期之间的年份差异

我试过这个,但它不计算闰年

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); 

结果来了 13.00789 应该小于 13

任何帮助将不胜感激

4

5 回答 5

12
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!");
} 
于 2013-01-09T08:55:22.947 回答
5

如果您有大量与日期相关的操作,请考虑使用 MomentJS http://momentjs.com/。检查那里的前两个示例,我想它们适合您的问题。

于 2013-01-09T08:54:52.373 回答
0

http://www.datejs.com/是一个有用的库,用于各种日期计算

于 2013-01-09T08:56:00.087 回答
0

采用

// millisecs * secs * mins * hrs * days (inclu. leap)
msecsInYear = 1000 * 60 * 60 * 24 * 365.25;  

注意:静态不正确,但在数学上是正确的!
将涵盖闰年的情况。

于 2018-04-17T09:07:48.857 回答
0
// 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');
}}}
于 2018-12-27T13:11:24.860 回答