表單驗證、用戶資料顯示常需根據生日算年齡。本文提供健壯的 GetAgeByBirthday 函數,支援多種日期格式輸入,含邊界檢查與錯誤處理。
// 解析多種日期字串為 Date 物件
function parseDate(str) {
if (str.match(/^\d{4}[-\/\s]\d{1,2}[-\/\s]\d{1,2}$/)) {
return new Date(str.replace(/[-\/\s]/g, '/'));
} else if (str.match(/^\d{8}$/)) {
return new Date(str.substring(0,4) + '/' + str.substring(4,6) + '/' + str.substring(6));
} else {
return '時間轉換發生錯誤!';
}
}
// 計算年齡
function GetAgeByBirthday(birthday) {
var age = -1;
var today = new Date();
var ty = today.getFullYear(), tm = today.getMonth() + 1, td = today.getDate();
var bday = parseDate(birthday);
if (bday == '時間轉換發生錯誤!') return -1;
var by = bday.getFullYear(), bm = bday.getMonth() + 1, bd = bday.getDate();
if (ty - by < 0) {
alert("出生日期選擇錯誤!");
return -1;
}
if (tm - bm < 0) {
age = ty - by - 1;
} else if (td - bd >= 0) {
age = ty - by;
} else {
age = ty - by - 1;
}
return age;
}
console.log(GetAgeByBirthday("1990-05-15")); // 2024-05-20 輸出 34
console.log(GetAgeByBirthday("19900515")); // 同上
console.log(GetAgeByBirthday("2025-01-01")); // 彈出錯誤提示,返回 -1
YYYY-MM-DD、YYYY/MM/DD、YYYYMMDD 等常見格式。可直接複製到專案工具庫,或改寫為 ES6 模組導出。