Skip to content
On this page

根据生日计算年龄

javascript
const birthdateReg = /^(\d{4})[-/]?(\d{1,2})[-/]?(\d{1,2})$/;
// birthday => 格式 年-月-日 例如: 2022-08-18
const calcAge = (birthday) => {
    const birthDateArr = birthdateReg.exec(`${birthday}`);
	// const birthDateArr = birthday.split('-').map(Number)
	// 获取出生年月日
	const [_, birthYear, birthMonth, birthDay] = birthDateArr;
	// 获取当前年月日
	const nowDate = new Date();
	const nowYear = nowDate.getFullYear();
	const nowMonth = nowDate.getMonth() + 1;
	const nowDay = nowDate.getDate();
	// 生日大于当前年份 不合法
	if (nowYear < birthYear) return -1;
	// 判断是否为同一年
	if (nowYear === +birthYear) {
	  if (nowMonth === +birthMonth) {// 同月
		  return nowDay >= birthDay ? 0 : -1;
	  }
	  return nowMonth > birthMonth ? 0 : -1;
  }
	// 不是同一年,计算年之差
	const yearDiff = nowYear - birthYear; //计算年差值
	// 当前年份之前出生
  if (nowMonth === +birthMonth) { // 月份相同
    const dayDiff = nowDay - birthDay; // 计算日差值
    return dayDiff < 0 ? (yearDiff - 1) : yearDiff
  }
  // 不同月份出生
  const monthDiff = nowMonth - birthMonth; //月之差
  return monthDiff < 0 ? (yearDiff - 1) : yearDiff;
}