年龄到出生日期计算(dd/mm/yyyy)格式不起作用

年龄到出生日期计算(dd/mm/yyyy)格式不起作用

问题描述:

我想从选定日期算起。从引导日期选择器,如果我使用mm/dd/yyyy代码工作正常,但如果格式为dd/mm/yyyy,并且如果我选择24/02/1992它是给我“NAN”。我的代码有什么问题。年龄到出生日期计算(dd/mm/yyyy)格式不起作用

我的代码是:

$('[name="dateOfBirth"]').change(function() { 
    $('[name="age"]').val(getAge(new Date($('[name="dateOfBirth"]').val())));   
}); 

function getAge(birthDate) { 
    var now = new Date(); 

    function isLeap(year) { 
      return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); 
    } 

    // days since the birthdate  
    var days = Math.floor((now.getTime() - birthDate.getTime())/1000/60/60/24); 
    var age = 0; 
    // iterate the years 
    for (var y = birthDate.getFullYear(); y <= now.getFullYear(); y++){ 
     var daysInYear = isLeap(y) ? 366 : 365; 
     if (days >= daysInYear){ 
      days -= daysInYear; 
      age++; 
      // increment the age only if there are available enough days for the year. 
      } 
    } 
    return age; 
}  

我使用dd/mm/yyyy格式得到日期选择出生日期。 我应该改变什么来获得超过12天的年龄,比如23/02/1992

任何帮助,将不胜感激。

+1

看到,如果你尚未使用moment.js。 http://momentjs.com/ –

+0

你问过之前你有没有搜索过? http://stackoverflow.com/questions/4060004/calculate-age-in-javascript – epascarello

+0

问题是,你正在使用String变量的.getTime方法。你需要使用该方法之前将其转换为日期变量 http://stackoverflow.com/questions/5619202/converting-string-to-date-in-js –

您可以简单地互换格式,而解析字符串到日期

$('[name="dateOfBirth"]').val().replace(/(\d{2}\/)(\d{2}\/)(\d{4})/,'$2$1$3')); 

console.log(new Date('24/02/1992'.replace(/(\d{2}\/)(\d{2}\/)(\d{4})/, '$2$1$3')));

+0

谢谢你的帮助:它工作正常现在。 –

+0

如果你要解析值,直接将它们传递给Date构造函数,不要创建一个新的字符串,可能只是原来的问题:'new Date(...'23/1/2017' .split(/ \ D /)。reverse())'这也是较少的类型。 ;-) – RobG

+0

@RobG,你的意思是'split()'和'reverse()'不会创建新的数组吗? – Arvind

您从字符串创建日期:new Date($('[name="dateOfBirth"]').val())

根据https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date

使用Date(dateString)构造函数时,值必须在特定的format中。

尝试做,如阿尔维德所说:修改日期以更正格式。

或提取年,月,日和使用Date(year, month, date)构造

+1

关注你的链接:“*不推荐使用Date.parse *”。使用Date构造函数解析字符串与使用Date.parse等效,使用库或编写简单的解析函数(2行代码)更好。 – RobG