计算方法考虑了闰年和平年
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
```