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
```
相关推荐
happy_0x3f5 分钟前
前端应用的离线暂停更新策略
开发语言·前端·php
shylyly_40 分钟前
C++中的类型转换
开发语言·c++·匿名对象·隐式类型转换·拷贝优化
新中地GIS开发老师1 小时前
零基础WebGIS开发入门 | GeoJSON数据持久化
前端·javascript·gis·webgis·三维gis开发
北冥you鱼1 小时前
Go 语言新手扫盲:指针 * 和 & 使用场景详解
开发语言·后端·golang
cui_ruicheng1 小时前
Python数据分析(一):数据分析概述与环境搭建
开发语言·python·数据分析
blns_yxl1 小时前
正则驱动实时表单验证(HTML+CSS+JS+正则)
javascript·css·html
心平气和量大福大2 小时前
C#-WPF-UserControl-生命周期(加载 退出)
开发语言·c#·wpf
sunywz2 小时前
【c#】 Web Deploy一键发布,IIS部署全流程
开发语言·前端·c#
Brilliantwxx2 小时前
【Linux】 软件包管理器(yum)+ Vim使用
linux·运维·服务器·开发语言·编辑器·vim
雪的季节2 小时前
Python 线程同步与异步编程 全解析
java·开发语言