javascript计算年龄

计算方法考虑了闰年和平年

typescript 复制代码
/**
 * 获取当前时间从年度开始至当前时间的毫秒数
 * 例如2026-06-13 18:00:00
 * 返回值为2026-01-11 00:00:00至2026-06-13 18:00:00之间的毫秒数
 */
Date.prototype.yearTime = function (this: Date) {
    const year = this.getFullYear();
    const month = this.getMonth() + 1;
    const day = this.getDate() - 1;

    let val = 0;
    for (let i = 1; i < month; ++i) {
        switch (i) {
            case 2:
                //闰年:29*86400000=2505600000
                //平年:28*86400000=2419200000
                val += (((year) % 4) == 0 && (((year) % 100) != 0 || ((year) % 400) == 0))
                    ? 2505600000 : 2419200000
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                //30*86400000=2592000000
                val += 2592000000
                break;
            default:
                //31*86400000=2,678,400,000
                val += 2678400000;
                break;
        }
    }
    val += (day * 86400000)
    return val;
}
/**
 * 计算年龄
 */
Date.prototype.age = function (this: Date, currentDate: Date) {
    const beginYear = this.getFullYear();
    const endYear = currentDate.getFullYear();
    let age = endYear - beginYear - 1;

    if (!currentDate.isLeap() && this.isLeap())
        return age + ((currentDate.yearTime() + 86400000) / this.yearTime());
    else if (currentDate.isLeap() && !this.isLeap())
        return age + ((currentDate.yearTime() - 86400000) / this.yearTime());
    else
        return age + (currentDate.yearTime() / this.yearTime());
};

使用方法

typescript 复制代码
const currentDate = new Date(2026, 11, 20);
const birth = new Date(1980, 11, 20);
const age = birth.age(currentDate);
console.log(age);
--46


const currentDate = new Date(2026, 6, 13);
const birth = new Date(1980, 11, 20);
const age = birth.age(currentDate);
console.log(age);
--45.548022598870055
```
相关推荐
时间的拾荒人35 分钟前
C语言字符函数与字符串函数完全指南
c语言·开发语言
2501_948106911 小时前
计算机毕业设计之基于jsp教科研信息共享系统
java·开发语言·信息可视化·spark·课程设计
取经蜗牛1 小时前
Python 第一阶段完全指南:从零到第一个实用工具
开发语言·python
anOnion2 小时前
Agentic 前端开发之 实时显示 AI Agent 终端输出
前端·javascript·人工智能
dog2502 小时前
从重尾到截断流量模型的演进
开发语言·php
这是个栗子2 小时前
【前端性能优化】优化数据加载:用 Promise.all 从串行到并行
前端·javascript·性能优化·异步编程·前端优化·promise.all
qq_401700412 小时前
Qt QSS 完全入门写出漂亮界面以及解决样式不生效问题
开发语言·qt
fei_sun3 小时前
黑洞路由(Null Route/空接口路由)
服务器·前端·javascript
我是一颗柠檬3 小时前
【Java项目技术亮点】覆盖索引与索引下推优化
android·java·开发语言
2601_962440843 小时前
计算机毕业设计之健身房管理系统的设计与实现
java·开发语言·课程设计·旅游·宠物