const onSelectDateChange = (e: any) => {
const now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1;
const day = now.getDate();
const myDate = new Date(e);
const myYear = myDate.getFullYear();
const myMonth = myDate.getMonth() + 1;
const myDay = myDate.getDate();
let gapDay = day - myDay;
if (gapDay < 0) {
month -= 1;
gapDay = getDaysOfMonth(e) - myDay + day;
}
let gapMonth = month - myMonth;
if (gapMonth < 0) {
year -= 1;
gapMonth = 12 - myMonth + month;
}
let gapYear = year - myYear;
if (gapYear < 0) {
gapYear = 0;
}
if (gapYear === 0) {
if (gapMonth === 0) {
const age = `${gapDay}天`;
form.setFieldsValue({
age,
});
} else {
const age = `${gapMonth}月`;
form.setFieldsValue({
age,
});
}
} else {
const age = `${gapYear}岁`;
form.setFieldsValue({
age,
});
}
};
// 获取当月的天数
const getDaysOfMonth = (age: any) => {
const date = new Date(age);
const year = date.getFullYear();
const mouth = date.getMonth() + 1;
let day = 0;
if (mouth === 2) {
day = isLeapYear(year) ? 29 : 28;
} else if (
mouth === 1 ||
mouth === 3 ||
mouth === 5 ||
mouth === 7 ||
mouth === 8 ||
mouth === 10 ||
mouth === 12
) {
day = 31;
} else {
day = 30;
}
return day;
};
// 判断是否为闰年
const isLeapYear = (year: any) => {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
};
JS(TS)计算年龄(精确到天数)(也可以将时间转换成moment格式,使用diff方法直接计算,两行代码就搞定了)
于 2021-01-12 17:56:23 首次发布