萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JS 根據出生日期精確計算年齡的工具函數

表單驗證、用戶資料顯示常需根據生日算年齡。本文提供健壯的 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 等常見格式。
  • 正確處理「生日尚未到」的情況(月份/日期比較)。
  • 輸入未來日期會彈窗提示並返回 -1,便於表單驗證攔截。
  • 純邏輯無副作用,易於單元測試與複用。

可直接複製到專案工具庫,或改寫為 ES6 模組導出。

copyright © 萬盛學電腦網 all rights reserved