const calculateAge = (birthDateString) => {
if (!birthDateString) return '未知';
const birthDate = new Date(birthDateString); // 转为日期对象
const today = new Date(); // 当前日期
// 基础年龄 = 当前年 - 出生年
let age = today.getFullYear() - birthDate.getFullYear();
// 关键修正:检查今年生日是否已过
const monthDiff = today.getMonth() - birthDate.getMonth();
if (
monthDiff < 0 || // 当前月份 < 出生月份
(monthDiff === 0 && today.getDate() < birthDate.getDate()) // 同月但当前日 < 出生日
) {
age--; // 生日未到,年龄减1
}
return age;
}
-
需要精确年龄(如法律、医疗场景)
✅ 保持当前calculateAge
实现
粗略年龄
// 简化为纯年份计算
const calculateAgeSimple = (birthDateString) => {
return birthDateString
? new Date().getFullYear() - new Date(birthDateString).getFullYear()
: '未知';
}
年龄范围计算,比如录入20-30岁的人
纯年份计算版
const convertAgeRange = () => {
const currentYear = new Date().getFullYear();
birthdateRange.value = { start: null, end: null };
// 最大年龄 → 最早出生年份(≥)
if (ageRange.value.max !== null && !isNaN(ageRange.value.max)) {
birthdateRange.value.start = currentYear - ageRange.value.max; // 例如50岁→1973年
}
// 最小年龄 → 最晚出生年份(≤)
if (ageRange.value.min !== null && !isNaN(ageRange.value.min)) {
birthdateRange.value.end = currentYear - ageRange.value.min; // 例如30岁→1993年
}
};
const convertAgeRangeByYear = () => {
const currentYear = new Date().getFullYear();
birthdateRange.value = { start: null, end: null };
// 处理最大年龄 → 出生日期最小值(≥)
if (ageRange.value.max !== null && !isNaN(ageRange.value.max)) {
// 最大年龄对应的最早出生年份 = 当前年份 - 最大年龄
// 使用该年份的1月1日 00:00:00
const birthYear = currentYear - ageRange.value.max;
birthdateRange.value.start = `${birthYear}-01-01 00:00:00`;
console.log("年龄开始时间:" + birthdateRange.value.start);
param.starBirth = birthdateRange.value.start;
}
// 处理最小年龄 → 出生日期最大值(≤)
if (ageRange.value.min !== null && !isNaN(ageRange.value.min)) {
// 最小年龄对应的最晚出生年份 = 当前年份 - 最小年龄
// 使用该年份的12月31日 23:59:59
const birthYear = currentYear - ageRange.value.min;
birthdateRange.value.end = `${birthYear}-12-31 23:59:59`;
console.log("年龄结束时间:" + birthdateRange.value.end)
param.endBirth = birthdateRange.value.end;
}
};
年月日的精确版
const birthdateRange = ref({ start: null, end: null });
// 以年月日计算年龄
const pad = (num) => num.toString().padStart(2, '0');
const convertAgeRange = () => {
const today = new Date();
const currentYear = today.getFullYear();
birthdateRange.value = { start: null, end: null };
// 最大年龄 → 最早出生日期(≥)
if (ageRange.value.max !== null && !isNaN(ageRange.value.max)) {
const birthYear = currentYear - ageRange.value.max - 1; // 生日可能未过
birthdateRange.value.start = `${birthYear}-${pad(today.getMonth()+1)}-${pad(today.getDate())} 00:00:00`;
}
// 最小年龄 → 最晚出生日期(≤)
if (ageRange.value.min !== null && !isNaN(ageRange.value.min)) {
const birthYear = currentYear - ageRange.value.min;
birthdateRange.value.end = `${birthYear}-${pad(today.getMonth()+1)}-${pad(today.getDate())} 23:59:59`;
}
};