在 JavaScript 中以 YYYY-MM-DD 格式计算给定出生日期的年龄
本文将介绍如何以 YYYY-MM-DD 格式计算给定出生日期的年龄。
在 JavaScript 中使用原生日期方法计算年龄给定 YYYY-MM-DD 格式的出生日期
给定 YYYY-MM-DD 的出生日期,我们可以使用本地日期方法来计算一个人的年龄。
const calculateAge = (birthday) => {
const ageDifMs = Date.now() - new Date(birthday).getTime();
const ageDate = new Date(ageDifMs);
return Math.abs(ageDate.getUTCFullYear() - 1970);
} console.log(calculateAge('1999-11-23'))
输出:
22
单击并访问此链接以查看上述示例的工作代码。
解释:
- 首先,我们使用生日输入构建了
calculateAge
函数,该函数需要一个日期字符串进行转换并用于计算年龄。 - 我们从函数中减去
Date.now
,其中包含当前日期时间的时间戳(以毫秒为单位)。 - 我们构建了一个新的 Date 实例。然后,我们调用
getTime
来获取我们经过的生日的毫秒精度时间戳。 - 然后将结果分配给
ageDifMs.
- 然后,我们将
ageDifMs
提供给日期函数Object() {[native code]}
以接收ageDate,
,它是 1970 年 1 月 1 日午夜 UTC 形成的日期,加上由我们过去的时间。
在 JavaScript 中使用 Moment.js
库以 YYYY-MM-DD 格式计算给定出生日期的年龄
我们还可以使用 Moment.js
库来简化日期计算。
const calculateAge = (birthday) => {
const startDate = new Date();
const endDate = new Date(birthday);
return Math.abs(moment.duration(endDate - startDate).years());
} console.log(calculateAge('1999-11-23'))
输出:
22
解释:
- 我们在
calculateAge
函数中使用了生日参数,和以前一样。 - 我们没有使用本地日期方法,而是使用
moment.duration
方法确定持续时间。 - 为了获取即时持续时间对象,我们用
endDate - startDate
调用它。 - 然后,我们用年数来表示时间长度。
- 然后,我们使用
Math.abs
再次检查结果是否为阳性。 - 控制台日志应显示与以前相同的信息。
使用 Vanilla JavaScript 以 YYYY-MM-DD 格式计算给定出生日期的年龄
首先,我们获取 HTML 文件并创建一个 <div>
,为其提供一个占位符 id,稍后将在 JavaScript 中调用 innerhtml
的函数时使用它。
<div id="placeholder">
<p>Changing Date of Birth in JavaScript</p>
</div>
然后,在 JS 文档中,我们首先创建一个变量 Date_of_Birth
来存储一个人的出生日期。
var Date_of_Birth = 'November 23, 1999';
var millisecondsBetweenDOBAnd1970 = Date.parse(Date_of_Birth);
var millisecondsBetweenNowAnd1970 = Date.now();
var ageInMilliseconds =
millisecondsBetweenNowAnd1970 - millisecondsBetweenDOBAnd1970;
var milliseconds = ageInMilliseconds;
var second = 1000;
var minute = second * 60;
var hour = minute * 60;
var day = hour * 24;
var month = day * 30;
var year = day * 365;
// Age is coverted by using tag `math`
var years = Math.round(milliseconds / year);
var months = years * 12;
var days = years * 365;
var hours = Math.round(milliseconds / hour);
var seconds = Math.round(milliseconds / second);
function printResults() {
var message = 'Age in Years : ' + years + '</br>Age in Months : ' + months +
'</br>Age in Days : ' + days + '</br>Age in Hours : ' + hours +
'</br>Age in Seconds : ' + seconds +
'</br>Age in Milliseconds : ' + milliseconds;
document.getElementById('placeholder').innerHTML = message;
}
window.onload = printResults;
输出:
Age in Years : 22
Age in Months : 264
Age in Days : 8030
Age in Hours : 195551
Age in Seconds : 703983954
Age in Milliseconds : 703983954456
你可以使用此链接运行此代码。
解释:
Date.parse()
函数解析日期字符串并返回从 1970 年 1 月 1 日午夜到该日期的毫秒数。自 1970 年 1 月 1 日起,Date.now()
函数返回毫秒数。
我们以这些函数为起点。为了保持 DOB/NOW 和 1970 年 1 月 1 日之间的毫秒数,我们建立了两个新变量 millisecondsBetweenDOBAnd1970
和 millisecondsBetweenNowAnd1970
。
然后,我们从 NOW 中减去 DOB 以找到一个人的年龄(以毫秒为单位)。当我们有一个人的以毫秒为单位的年龄时,我们必须实现一些基本逻辑来将其转换为年、月、日、小时、分钟和秒。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。