Vg.*_*Vg. 3 html javascript jquery datepicker
我想计算使用 jquery 日期选择器选择日期时的年龄。我在下面添加了代码,但如果我选择“19/03/2015”、“15/01/2015”或“19/03/2014”、“31/12/2014”等日期,它会显示负值
$(document).ready(function ()
{
console.log($(document).width());
$('#patientDob').datepicker
({
dateFormat: 'dd/mm/yy',
changeMonth: true,
changeYear: true,
yearRange: '1900:2150',
maxDate: new Date(),
inline: true,
onSelect: function() {
var birthDay = document.getElementById("patientDob").value;
var DOB = new Date(birthDay);
var today = new Date();
var age = today.getTime() - DOB.getTime();
age = Math.floor(age / (1000 * 60 * 60 * 24 * 365.25));
document.getElementById('patientAge').value = age;
}
});
});
Run Code Online (Sandbox Code Playgroud)
我使用 jQuery UI 为我的项目创建了这个年龄计算器。和 JavaScript 函数。你会得到准确的结果。
它将计算年龄并显示为人类可读的。创建一个 ID 为“datepicker”的日期字段并导入 jquery 和 jquery ui 。在那之后
然后只需复制并粘贴代码即可获得准确的结果。
输出 // 28 年 7 个月 7 天
$(function () {
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
showAnim: 'slideDown',
dateFormat: 'yy-mm-dd'
}).on('change', function () {
var age = getAge(this);
/* $('#age').val(age);*/
console.log(age);
alert(age);
});
function getAge(dateVal) {
var
birthday = new Date(dateVal.value),
today = new Date(),
ageInMilliseconds = new Date(today - birthday),
years = ageInMilliseconds / (24 * 60 * 60 * 1000 * 365.25 ),
months = 12 * (years % 1),
days = Math.floor(30 * (months % 1));
return Math.floor(years) + ' years ' + Math.floor(months) + ' months ' + days + ' days';
}
Run Code Online (Sandbox Code Playgroud)
});
| 归档时间: |
|
| 查看次数: |
12273 次 |
| 最近记录: |