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
```
相关推荐
SomeB1oody8 分钟前
【RustyML入门】3.8. 正则化与归一化层
开发语言·后端·机器学习·rust·教程
__zRainy__11 分钟前
Node系列 · Node基础:全局变量与全局对象
开发语言·前端·javascript
sunly_27 分钟前
TypeScript总结:15、类型速查
前端·javascript·typescript
Brown.alexis27 分钟前
es6知识点3-自备使用
前端·javascript·es6
breeze jiang42 分钟前
Next.js App Router 父子组件 RSC 拆分实战:从 Redis Hash 到客户端交互的最小化边界
javascript·redis·哈希算法
丫头,冲鸭!!!1 小时前
记账网站-post功能
javascript·个人开发
鬼手点金1 小时前
Scrapy + Playwright 完整示例(JS 动态渲染网页)
开发语言·javascript·爬虫·python·scrapy·html·json
Mr. zhihao1 小时前
深度解析:为什么Java序列化需要搭配ByteArrayOutputStream?IO装饰器模式的精妙设计
java·开发语言·装饰器模式
格林威1 小时前
多相机并行采图最佳实践:Task.WhenAll + 异常处理 + 资源释放
开发语言·人工智能·数码相机·计算机视觉·c#·视觉检测·机器视觉
djjjx.1 小时前
【 C++ 】多态
开发语言·c++·多态