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
```
相关推荐
柚yuzumi7 分钟前
前端优化,从少触发一次开始:防抖与节流
前端·javascript
源代码•宸14 分钟前
前置准备:定时微服务背景和现状
开发语言·经验分享·后端·微服务·云原生·架构·golang
2601_9673387114 分钟前
C#上位机开发零基础入门到精通全套视频
开发语言·c#
默_笙29 分钟前
🚤 CSS 布局的"圈地运动":BFC 就是浏览器的独立领地
前端·javascript
用户938515635071 小时前
大模型记忆指南:从短时缓存到永久记忆,手把手带你吃透 LangChain Memory 管理
javascript·人工智能
小白学大数据1 小时前
超简单:用 Python 让 Excel 飞起来:用 openpyxl 把重复报表整理交给脚本
开发语言·数据库·python·excel
旧梦95271 小时前
Java SortedMap 接口详解:从入门到实战
java·开发语言
xqchen1 小时前
Web Components 普及困境深度解析:技术标准与工程实践的落差
javascript
莫陌尛.1 小时前
Java_this构造方法
java·开发语言
爱丶不疚1 小时前
写给前端工程师的现代 Python 工程化最佳实践:从 pnpm 到 uv,从 CommonJS 到 src-layout
javascript·python·typescript