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
```
相关推荐
Dick5071 小时前
ROS2 多机器人通用 Driver 层复盘:BaseRobotDriver 到多平台 Mock 切换实现
前端·javascript·机器人
肖爱Kun2 小时前
STL标准模块库操作
开发语言·音视频
Song_da_da_2 小时前
C# 接口(Interface)深度解析:规范、解耦与灵活扩展
开发语言·c#
政沅同学2 小时前
基于 C# WPF + HALCON 的工业视觉算法工具框架(开源)
开发语言·c#·wpf
影寂ldy2 小时前
C#WinForm 窗体基础(入口、部分类、属性、生命周期事件)
开发语言·c#
2301_781833522 小时前
Python 正则表达式入门教程
开发语言·python·正则表达式
gihigo19982 小时前
基于蒙特卡洛的异常值剔除(RANSAC + MC置信区间)—MATLAB实现
开发语言·算法·matlab
Ting.~2 小时前
在java中接入百度地图
java·开发语言·dubbo