根據出生日期計算星座、生肖、年齡是常見需求(註冊資料補全、個人化推薦、年齡驗證)。本文提供生產就緒的 PHP 函數庫,涵蓋邊界處理、閏年計算、效能優化與單元測試範例。
| 星座 | 起始日期 | 結束日期 | 符號 |
|---|---|---|---|
| 摩羯座 | 12/22 | 01/19 | ♑ |
| 水瓶座 | 01/20 | 02/18 | ♒ |
| 雙魚座 | 02/19 | 03/20 | ♓ |
| 白羊座 | 03/21 | 04/19 | ♈ |
| 金牛座 | 04/20 | 05/20 | ♉ |
| 雙子座 | 05/21 | 06/21 | ♊ |
| 巨蟹座 | 06/22 | 07/22 | ♋ |
| 獅子座 | 07/23 | 08/22 | ♌ |
| 處女座 | 08/23 | 09/22 | ♍ |
| 天秤座 | 09/23 | 10/23 | ♎ |
| 天蠍座 | 10/24 | 11/22 | ♏ |
| 射手座 | 11/23 | 12/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 預設摩羯座
}
?>
<?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); // 午馬
?>
當前年份 - 出生年份 + 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
?>
<?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
)
*/
?>
<?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
// 此處略
}
}
?>
checkdate() 會驗證閏年。非閏年 2/29 視為無效。年齡計算中,DateTime 會自動將 2/29 視為 3/1 (非閏年),format('md') 比較仍正常運作。new DateTimeZone('Asia/Taipei'),避免伺服器時區導致生日判斷偏差一天。提供三個核心函數 getZodiac()、getChineseZodiac()、getExactAge() 及整合類別 BirthdayInfo,涵蓋驗證、邊界、時區、閏年、效能。直接複製到專案即可生產使用,並附帶 PHPUnit 測試範例確保正確性。