Iam通过保留今天日期和选定日期来计算年龄。jQuery年龄计算不计算闰年
如果我说今天(28日2016年4月) - 精确3年正确显示
如果我说昨日(27日2016年4月) - 仍然3年正在显示,这不应该是因为1天较少为3年。我不知道iam在我的代码中做错了什么。
感谢您的帮助!
示例代码:
var getMonth, getDay, getYear, getDate, dob, today, age;
$(document).on('change', '#node_enfamama_registration_form_form_group_enr_hide_child_info .form-select', function() {
$(this).each(function() {
if ($(this).parents().hasClass('date-month')) {
getMonth = $(this).val();
alert(getMonth)
}
else if ($(this).parents().hasClass('date-day')) {
getDay = $(this).val();
alert(getDay)
}
else if ($(this).parents().hasClass('date-year')) {
getYear = $(this).val();
alert(getYear)
getDate = getYear + "-" + getMonth + "-" + getDay;
alert("Month, day & year" + getDate)
$('.greater-msg').remove();
$('.less-then-msg').remove();
dob = new Date(getDate);
today = new Date();
age = Math.floor((today - dob)/(365.25 * 24 * 60 * 60 * 1000));
alert("Child Age is " + age)
//debugger;
/*
var birthDate = new Date(getDate);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
alert("aaa" + age)
age--;
}*/
if (age > 3) {
//debugger;
$(this).parents('.fieldset-wrapper').after('<div class="greater-msg">You can also visit <a href="http://www.enfagrow4.com" target="_blank">www.enfagrow4.com</a> to know how you can keep giving your child the 360 advantage.</div>')
} else if (age <= -1) {
//$(this).parents('.fieldset-wrapper').after('<div class="less-then-msg">Less Disclaimer: In compliance with EO51, Mead Johnson Nutrition cannot directly engage with mothers with children aged 0 to 3 years old. All content that you will receive via email will only be regarding your pregnancy. </div>')
} else if (age >= 0 && age <= 3) {
$(this).parents('.fieldset-wrapper').after('<div class="less-then-msg">Less Disclaimer: In compliance with EO51, Mead Johnson Nutrition cannot directly engage with mothers with children aged 0 to 3 years old. All content that you will receive via email will only be regarding your pregnancy. </div>')
} else {
}
function checkDate(){
}
} else {}
});
});
你能具体谈谈你如何测试?我做了以下事情:选择28-april-2013 =>我的孩子是3.正确的。选择27-april-2013 => 3正确(因为他是3天和1天)。选择29-april-2013 => 2正确(多一天到三天)。然后我今天在JavaScript中设置为昨天(今天=新日期('2016-04-27')),并选择2013年4月28日=> 2正确。 – Laura
使用[momentjs](http://momentjs.com/docs/#/manipulating/add/)来计算日期 –
@Laura:谢谢,正确,选择27-april-2013 => 3正确(因为他是3和1天),然后警报(“你也可以访问”)消息应该显示。 –