萬盛學電腦網

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

JavaScript 根據出生日期精確計算年齡 (周歲/虛歲) 完整函數

年齡計算核心邏輯

**周歲 (國際通用)**:以生日為分界,生日未到不加 1。
**虛歲 (傳統東亞)**:出生即 1 歲,每逢農曆新年加 1 (本文專注周歲)。

健壯的周歲計算函數 (原生 JS)

/**
 * 計算周歲
 * @param {String|Date} birthDate - 出生日期,支援 'YYYY-MM-DD', 'YYYY/MM/DD', Date 物件
 * @param {Date} [referenceDate=new Date()] - 計算基準日 (預設今天)
 * @returns {Number} 周歲,無效輸入回傳 null
 */
function calculateAge(birthDate, referenceDate) {
    var ref = referenceDate || new Date();
    var birth;
    
    // 解析輸入
    if (birthDate instanceof Date) {
        birth = birthDate;
    } else if (typeof birthDate === 'string') {
        // 支援 YYYY-MM-DD、YYYY/MM/DD、YYYY.MM.DD
        var parts = birthDate.split(/[-/.]/);
        if (parts.length !== 3) return null;
        var y = parseInt(parts[0], 10);
        var m = parseInt(parts[1], 10) - 1; // JS 月份 0-11
        var d = parseInt(parts[2], 10);
        birth = new Date(y, m, d);
        // 驗證日期有效性 (自動處理 2/30 等無效日期會自動轉為 3/2)
        if (birth.getFullYear() !== y || birth.getMonth() !== m || birth.getDate() !== d) {
            return null; // 無效日期
        }
    } else {
        return null;
    }
    
    // 未來日期檢查
    if (birth > ref) return null;
    
    // 核心計算:年份差 - (今年生日是否已過 ? 0 : 1)
    var age = ref.getFullYear() - birth.getFullYear();
    var hasHadBirthday = (ref.getMonth() > birth.getMonth()) || 
                         (ref.getMonth() === birth.getMonth() && ref.getDate() >= birth.getDate());
    
    if (!hasHadBirthday) age--;
    
    return age;
}

// 使用範例
console.log(calculateAge('1990-05-15'));           // 今日 2024-12-19 → 34
console.log(calculateAge('2010-12-20'));           // 生日未到 → 13
console.log(calculateAge('2010-12-18'));           // 生日已過 → 14
console.log(calculateAge('2025-01-01'));           // 未來日期 → null
console.log(calculateAge('invalid'));              // 格式錯誤 → null
console.log(calculateAge('2000-02-29', new Date('2024-02-28'))); // 閏年出生,非閏年 2/28 → 23 (生日未到)
console.log(calculateAge('2000-02-29', new Date('2024-03-01'))); // 3/1 → 24 (生日已過,視同 2/28 或 3/1 視業務定義)

進階:回傳詳細資訊物件

function getAgeDetail(birthDate, referenceDate) {
    var age = calculateAge(birthDate, referenceDate);
    if (age === null) return { valid: false, error: '無效出生日期' };
    
    var ref = referenceDate || new Date();
    var birth = birthDate instanceof Date ? birthDate : new Date(birthDate.split(/[-/.]/)[0], 
        parseInt(birthDate.split(/[-/.]/)[1], 10) - 1, 
        parseInt(birthDate.split(/[-/.]/)[2], 10));
    
    var nextBirthday = new Date(ref.getFullYear(), birth.getMonth(), birth.getDate());
    if (nextBirthday < ref) nextBirthday.setFullYear(ref.getFullYear() + 1);
    
    var diffMs = nextBirthday - ref;
    var daysLeft = Math.ceil(diffMs / (1000 * 60 * 60 * 24));
    
    return {
        valid: true,
        age: age,
        birthDate: birth.toISOString().split('T')[0],
        nextBirthday: nextBirthday.toISOString().split('T')[0],
        daysUntilBirthday: daysLeft,
        zodiac: getZodiac(birth),      // 生肖
        constellation: getConstellation(birth) // 星座
    };
}

// 生肖計算 (以農曆新年為界,此處簡化用立春/元旦,精確需農曆庫)
function getZodiac(date) {
    var zodiacs = ['鼠','牛','虎','兔','龍','蛇','馬','羊','猴','雞','狗','豬'];
    // 1900 是鼠年
    return zodiacs[(date.getFullYear() - 1900) % 12];
}

// 星座計算 (陽曆)
function getConstellation(date) {
    var m = date.getMonth() + 1, d = date.getDate();
    var constellations = [
        {name:'摩羯', start:[1,20]}, {name:'水瓶', start:[2,19]}, {name:'雙魚', start:[3,21]},
        {name:'牡羊', start:[4,20]}, {name:'金牛', start:[5,21]}, {name:'雙子', start:[6,21]},
        {name:'巨蟹', start:[7,23]}, {name:'獅子', start:[8,23]}, {name:'處女', start:[9,23]},
        {name:'天秤', start:[10,23]}, {name:'天蠍', start:[11,22]}, {name:'射手', start:[12,22]},
        {name:'摩羯', start:[12,32]} // 結界
    ];
    for (var i = 0; i < 12; i++) {
        var s = constellations[i].start;
        var e = constellations[i+1].start;
        if ((m === s[0] && d >= s[1]) || (m === e[0] && d < e[1])) return constellations[i].name + '座';
    }
    return '摩羯座';
}

// 測試
console.log(getAgeDetail('1990-05-15'));
/*
{
  valid: true,
  age: 34,
  birthDate: "1990-05-15",
  nextBirthday: "2025-05-15",
  daysUntilBirthday: 147,
  zodiac: "馬",
  constellation: "金牛座"
}
*/

常見錯誤寫法與修正

錯誤寫法問題修正
new Date().getFullYear() - birthYear未判斷生日是否已過,會多算 1 歲比較月日,未過則 -1
new Date(birthStr) 直接解析字串格式不標準時行為不一致 (Safari 不支援 YYYY-MM-DD)手動拆分年月日用 new Date(y, m-1, d)
用 getTime() 相減除以 365.25閏年、月份長短不同導致誤差用年份差 + 月日比較法

現代化:Intl.RelativeTimeFormat (僅顯示用)

// 顯示「34 歲」本地化字串
function formatAge(age, locale = 'zh-TW') {
    return new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }).format(-age, 'year');
    // zh-TW: "34 年前" (需配合邏輯調整為 "34 歲")
}

總結

精確計算周歲的關鍵:**年份差 - (今年生日是否已過 ? 1 : 0)**。務必驗證輸入日期有效性、處理閏年邊界 (2/29)、支援多種日期格式。建議封裝為工具函數庫 (如 date-fns、dayjs 的 age plugin) 專案統一使用。

copyright © 萬盛學電腦網 all rights reserved