年龄到出生日期计算(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
。
任何帮助,将不胜感激。
答
您可以简单地互换格式,而解析字符串到日期
$('[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')));
答
您从字符串创建日期: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
看到,如果你尚未使用moment.js。 http://momentjs.com/ –
你问过之前你有没有搜索过? http://stackoverflow.com/questions/4060004/calculate-age-in-javascript – epascarello
问题是,你正在使用String变量的.getTime方法。你需要使用该方法之前将其转换为日期变量 http://stackoverflow.com/questions/5619202/converting-string-to-date-in-js –