萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 根據生日計算星座、生肖與年齡:完整函數庫與邏輯詳解

前言

根據出生日期計算星座、生肖、年齡是常見需求(註冊資料補全、個人化推薦、年齡驗證)。本文提供生產就緒的 PHP 函數庫,涵蓋邊界處理、閏年計算、效能優化與單元測試範例。

一、星座計算

星座日期區間表 (太陽曆)

星座起始日期結束日期符號
摩羯座12/2201/19♑
水瓶座01/2002/18♒
雙魚座02/1903/20♓
白羊座03/2104/19♈
金牛座04/2005/20♉
雙子座05/2106/21♊
巨蟹座06/2207/22♋
獅子座07/2308/22♌
處女座08/2309/22♍
天秤座09/2310/23♎
天蠍座10/2411/22♏
射手座11/2312/21♐

高效能實作:二分搜尋 / 閾值陣列

<?php
/**
 * 根據月、日計算星座
 * @param int $month 1-12
 * @param int $day   1-31
 * @return string 星座名稱
 * @throws InvalidArgumentException 日期無效
 */
function getZodiac(int $month, int $day): string {
    // 邊界驗證
    if ($month < 1 || $month > 12 || $day < 1 || $day > 31) {
        throw new InvalidArgumentException("無效日期: $month-$day");
    }
    // 進一步驗證實際天數 (含閏年)
    $daysInMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    if ($day > $daysInMonth[$month - 1]) {
        throw new InvalidArgumentException("無效日期: $month-$day");
    }

    // 閾值:每個星座的「起始月日」轉為 年內第幾天 (非閏年基準)
    // 摩羯座跨年,特殊處理:12/22 之後或 1/19 之前
    $boundaries = [
        [1, 20, '水瓶座'],   // 01/20
        [2, 19, '雙魚座'],   // 02/19
        [3, 21, '白羊座'],   // 03/21
        [4, 20, '金牛座'],   // 04/20
        [5, 21, '雙子座'],   // 05/21
        [6, 22, '巨蟹座'],   // 06/22
        [7, 23, '獅子座'],   // 07/23
        [8, 23, '處女座'],   // 08/23
        [9, 23, '天秤座'],   // 09/23
        [10, 24, '天蠍座'],  // 10/24
        [11, 23, '射手座'],  // 11/23
        [12, 22, '摩羯座'],  // 12/22
    ];

    // 計算當前日期是年內第幾天 (1/1 = 1)
    $dayOfYear = (int)date('z', mktime(0, 0, 0, $month, $day)) + 1;

    // 計算各星座起始日的年內第幾天
    $starts = [];
    foreach ($boundaries as [$m, $d, $name]) {
        $starts[] = [(int)date('z', mktime(0, 0, 0, $m, $d)) + 1, $name];
    }

    // 二分搜尋或線性查找 (12筆資料線性足夠快)
    $zodiac = '摩羯座'; // 預設 (12/22 前 或 1/19 後)
    foreach ($starts as [$startDay, $name]) {
        if ($dayOfYear >= $startDay) {
            $zodiac = $name;
        } else {
            break;
        }
    }
    return $zodiac;
}

// 測試
echo getZodiac(1, 19);  // 摩羯座
echo getZodiac(1, 20);  // 水瓶座
echo getZodiac(12, 21); // 射手座
echo getZodiac(12, 22); // 摩羯座
?>

簡化版:直接比對月日 (效能略低但程式碼極簡)

<?php
function getZodiacSimple(int $month, int $day): string {
    $zodiacs = [
        ['month' => 1,  'day' => 20, 'name' => '水瓶座'],
        ['month' => 2,  'day' => 19, 'name' => '雙魚座'],
        ['month' => 3,  'day' => 21, 'name' => '白羊座'],
        ['month' => 4,  'day' => 20, 'name' => '金牛座'],
        ['month' => 5,  'day' => 21, 'name' => '雙子座'],
        ['month' => 6,  'day' => 22, 'name' => '巨蟹座'],
        ['month' => 7,  'day' => 23, 'name' => '獅子座'],
        ['month' => 8,  'day' => 23, 'name' => '處女座'],
        ['month' => 9,  'day' => 23, 'name' => '天秤座'],
        ['month' => 10, 'day' => 24, 'name' => '天蠍座'],
        ['month' => 11, 'day' => 23, 'name' => '射手座'],
        ['month' => 12, 'day' => 22, 'name' => '摩羯座'],
    ];
    
    foreach ($zodiacs as $z) {
        if ($month > $z['month'] || ($month === $z['month'] && $day >= $z['day'])) {
            $result = $z['name'];
        }
    }
    return $result ?? '摩羯座'; // 1/1-1/19 預設摩羯座
}
?>

二、生肖計算

十二生肖對應表 (以 1900 年為子鼠年基準)

<?php
/**
 * 根據出生年份計算生肖
 * @param int $year 出生年份 (如 1990)
 * @return string 生肖名稱
 */
function getChineseZodiac(int $year): string {
    $animals = [
        '子鼠', '丑牛', '寅虎', '卯兔', '辰龍', '巳蛇',
        '午馬', '未羊', '申猴', '酉雞', '戌狗', '亥豬'
    ];
    // 1900 年是子鼠年 (索引 0)
    // 負數年份 (公元前) PHP 模運算結果為負,需修正
    $index = (($year - 1900) % 12 + 12) % 12;
    return $animals[$index];
}

// 測試
echo getChineseZodiac(2024); // 辰龍
echo getChineseZodiac(2000); // 辰龍
echo getChineseZodiac(1990); // 午馬
?>

三、年齡計算

虛歲 vs 周歲

  • 虛歲 (傳統歲數):出生即 1 歲,每過一個農曆新年 +1。近似 當前年份 - 出生年份 + 1。
  • 周歲 (實足年齡):出生 0 歲,每過一個生日 +1。國際通用、法律效力。

精確周歲計算 (支援閏年、時區)

<?php
/**
 * 計算精確周歲
 * @param int $birthYear
 * @param int $birthMonth
 * @param int $birthDay
 * @param DateTimeZone|null $tz 時區 (預設系統時區)
 * @return int 周歲
 */
function getExactAge(int $birthYear, int $birthMonth, int $birthDay, ?DateTimeZone $tz = null): int {
    $birth = new DateTime("$birthYear-$birthMonth-$birthDay", $tz);
    $now = new DateTime('now', $tz);
    
    // 若生日尚未到達,年齡 -1
    $age = $now->format('Y') - $birth->format('Y');
    if ($now->format('md') < $birth->format('md')) {
        $age--;
    }
    return max(0, $age);
}

/**
 * 計算虛歲
 */
function getNominalAge(int $birthYear, int $birthMonth, int $birthDay, ?DateTimeZone $tz = null): int {
    $now = new DateTime('now', $tz);
    $age = $now->format('Y') - $birthYear + 1;
    return max(1, $age);
}

// 測試 (假設今天 2024-06-15)
echo getExactAge(2000, 6, 14); // 24 (生日已過)
echo getExactAge(2000, 6, 16); // 23 (生日未到)
echo getNominalAge(2000, 6, 15); // 25
?>

四、整合類別:BirthdayInfo

<?php
class BirthdayInfo {
    public function __construct(
        public readonly int $year,
        public readonly int $month,
        public readonly int $day,
        private readonly ?DateTimeZone $tz = null
    ) {
        // 驗證日期合法性
        if (!checkdate($month, $day, $year)) {
            throw new InvalidArgumentException("無效出生日期: $year-$month-$day");
        }
    }

    public function getZodiac(): string { return getZodiac($this->month, $this->day); }
    public function getChineseZodiac(): string { return getChineseZodiac($this->year); }
    public function getExactAge(): int { return getExactAge($this->year, $this->month, $this->day, $this->tz); }
    public function getNominalAge(): int { return getNominalAge($this->year, $this->month, $this->day, $this->tz); }
    
    public function getNextBirthday(): DateTime {
        $now = new DateTime('now', $this->tz);
        $next = new DateTime($now->format('Y') . "-{$this->month}-{$this->day}", $this->tz);
        if ($next <= $now) $next->modify('+1 year');
        return $next;
    }
    
    public function getDaysUntilBirthday(): int {
        $now = new DateTime('now', $this->tz);
        $next = $this->getNextBirthday();
        return (int)$now->diff($next)->format('%a');
    }
    
    public function toArray(): array {
        return [
            'birth_date' => sprintf('%04d-%02d-%02d', $this->year, $this->month, $this->day),
            'zodiac' => $this->getZodiac(),
            'chinese_zodiac' => $this->getChineseZodiac(),
            'exact_age' => $this->getExactAge(),
            'nominal_age' => $this->getNominalAge(),
            'days_until_birthday' => $this->getDaysUntilBirthday(),
            'next_birthday' => $this->getNextBirthday()->format('Y-m-d')
        ];
    }
}

// 使用範例
$info = new BirthdayInfo(1995, 8, 15);
print_r($info->toArray());
/*
Array
(
    [birth_date] => 1995-08-15
    [zodiac] => 獅子座
    [chinese_zodiac] => 亥豬
    [exact_age] => 28
    [nominal_age] => 30
    [days_until_birthday] => 45
    [next_birthday] => 2024-08-15
)
*/
?>

五、單元測試範例 (PHPUnit)

<?php
use PHPUnit\Framework\TestCase;

class BirthdayTest extends TestCase {
    public function testZodiacBoundaries() {
        $this->assertEquals('摩羯座', getZodiac(1, 1));
        $this->assertEquals('摩羯座', getZodiac(1, 19));
        $this->assertEquals('水瓶座', getZodiac(1, 20));
        $this->assertEquals('水瓶座', getZodiac(2, 18));
        $this->assertEquals('射手座', getZodiac(12, 21));
        $this->assertEquals('摩羯座', getZodiac(12, 22));
        $this->assertEquals('摩羯座', getZodiac(12, 31));
    }
    
    public function testChineseZodiacCycle() {
        $this->assertEquals('子鼠', getChineseZodiac(1900));
        $this->assertEquals('丑牛', getChineseZodiac(1901));
        $this->assertEquals('亥豬', getChineseZodiac(1911));
        $this->assertEquals('子鼠', getChineseZodiac(1912)); // 循環
        $this->assertEquals('辰龍', getChineseZodiac(2024));
    }
    
    public function testExactAge() {
        // 模擬固定時間需使用 timecop 或注入 DateTime
        // 此處略
    }
}
?>

六、常見問題與避坑指南

Q: 星座日期網上版本不一致?
A: 星座分界點每年因太陽黃經略有漂移 (約幾小時)。本文採用最通用的「固定公曆日期」定義,符合大多數應用場景。精確天文計算需引入 Swiss Ephemeris 等天文庫。
Q: 2 月 29 日出生怎麼辦?
A: checkdate() 會驗證閏年。非閏年 2/29 視為無效。年齡計算中,DateTime 會自動將 2/29 視為 3/1 (非閏年),format('md') 比較仍正常運作。
Q: 時區影響年齡計算?
A: 是。跨國應用請傳入用戶時區 new DateTimeZone('Asia/Taipei'),避免伺服器時區導致生日判斷偏差一天。

總結

提供三個核心函數 getZodiac()、getChineseZodiac()、getExactAge() 及整合類別 BirthdayInfo,涵蓋驗證、邊界、時區、閏年、效能。直接複製到專案即可生產使用,並附帶 PHPUnit 測試範例確保正確性。

copyright © 萬盛學電腦網 all rights reserved