「用今年減去年」算年齡是常見的錯誤寫法,因為沒考慮到生日還沒到。正確做法必須比較三層:年、月、日。本文提供一個會先驗證日期格式、再逐層判斷的完整實作。
// 把多種格式的日期字串轉成 Date 物件
function parseDate(str) {
if (str.match(/^\d{4}[\-\/\s+]\d{1,2}[\-\/\s+]\d{1,2}$/)) {
// 2026-08-26 / 2026/8/6 這類格式
return new Date(str.replace(/[\-\/\s+]/i, '/'));
} else if (str.match(/^\d{8}$/)) {
// 20260826 這種純數字格式
return new Date(str.substring(0, 4) + '/' + str.substring(4, 6) + '/' + str.substring(6));
} else {
return '時間轉換發生錯誤!';
}
}
function GetAgeByBrithday(birthday) {
var today = new Date();
var todayYear = today.getFullYear();
var todayMonth = today.getMonth() + 1;
var todayDay = today.getDate();
var birth = parseDate(birthday);
if (birth === '時間轉換發生錯誤!') return -1;
var birthYear = birth.getFullYear();
var birthMonth = birth.getMonth() + 1;
var birthDay = birth.getDate();
if (todayYear - birthYear < 0) {
alert("出生日期選擇錯誤!");
return -1;
}
var age = todayYear - birthYear;
// 今年的生日還沒到,年齡要減一
if (todayMonth < birthMonth ||
(todayMonth === birthMonth && todayDay < birthDay)) {
age--;
}
return age;
}
核心邏輯只有一句:先減年份,再看今年的生日過了沒。生日還沒到就減一歲。原範例用「月份相乘再比較」的方式來處理,雖然結果多半正確,但改成上面的直接比較更直覺,也不容易出錯。
原範例中還有個 bug:birthdayMonth = birthday.getMonth() 忘了加 1,導致月份判斷整整差一個月。上面已修正。
如果格式固定為 YYYY-MM-DD,其實不需要那麼多程式碼:
function calcAge(birthday) {
var birth = new Date(birthday);
var today = new Date();
var age = today.getFullYear() - birth.getFullYear();
var m = today.getMonth() - birth.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birth.getDate())) age--;
return age;
}
console.log(calcAge('1990-08-26'));
閏年二月生的人怎麼辦?2 月 29 日出生者在平年沒有生日。實務上常見的約定是「平年以 3 月 1 日為準」或「以 2 月 28 日為準」,這牽涉法律與行政慣例,實作前最好先確認需求方採哪一種。
時區會造成一天的誤差。new Date('1990-08-26') 這種「純日期字串」會被解析為 UTC 午夜,在 UTC+8 或更西的時區可能落到前一天。要避開這個問題,建議改用 new Date(1990, 7, 26)(月份從 0 起算)這種明確的建構方式,或引入 date-fns、Day.js 等函式庫處理。
最後,函式名稱拼成了 Brithday(正確拼法為 Birthday),複製使用時建議一併更正,避免拼字錯誤在程式碼中擴散。