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天),然後警報(「你也可以訪問」)消息應該顯示。 –