gpt4 book ai didi

javascript - 如何从 jquery datepicker 计算年龄?

转载 作者:行者123 更新时间:2023-11-30 16:59:30 25 4
gpt4 key购买 nike

我想在使用 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;
}
});

});

最佳答案

我为我的项目创建了这个年龄计算器使用 jQuery 用户界面。和 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';

}

});

关于javascript - 如何从 jquery datepicker 计算年龄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29137763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com