gpt4 book ai didi

javascript - 年龄计算

转载 作者:可可西里 更新时间:2023-11-01 01:55:06 25 4
gpt4 key购买 nike

有 2 个 javascript 日期,

首先是生日第二个是从该日期开始计算年龄的日期。

执行此操作的最佳方法应该是什么。

最佳答案

function calculateAge (birthDate, otherDate) {
birthDate = new Date(birthDate);
otherDate = new Date(otherDate);

var years = (otherDate.getFullYear() - birthDate.getFullYear());

if (otherDate.getMonth() < birthDate.getMonth() ||
otherDate.getMonth() == birthDate.getMonth() && otherDate.getDate() < birthDate.getDate()) {
years--;
}

return years;
}

例子:

var age = calculateAge("02/24/1991", "02/24/2010"); // Format: MM/DD/YYYY

关于javascript - 年龄计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4076321/

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