Classic ASP (VBScript) 函數:傳入 MMDD 格式日期字串 (如 "0126" 代表 1 月 26 日),回傳對應星座中文名稱。適用於星座運勢、會員資料補全等場景。
<%
' ==========================================
' 根據月日判斷星座
' @param strDate 字串,格式 MMDD (如 "0126")
' @return 星座中文名稱
' ==========================================
Function GetConstellation(strDate)
If Len(strDate) <> 4 Then GetConstellation = "格式錯誤" : Exit Function
Dim m, d
m = CInt(Left(strDate, 2))
d = CInt(Right(strDate, 2))
' 邊界日期判斷 (依國際標準劃分)
Select Case m
Case 1 : If d >= 20 Then GetConstellation = "水瓶座" Else GetConstellation = "摩羯座"
Case 2 : If d >= 19 Then GetConstellation = "雙魚座" Else GetConstellation = "水瓶座"
Case 3 : If d >= 21 Then GetConstellation = "白羊座" Else GetConstellation = "雙魚座"
Case 4 : If d >= 20 Then GetConstellation = "金牛座" Else GetConstellation = "白羊座"
Case 5 : If d >= 21 Then GetConstellation = "雙子座" Else GetConstellation = "金牛座"
Case 6 : If d >= 22 Then GetConstellation = "巨蟹座" Else GetConstellation = "雙子座"
Case 7 : If d >= 23 Then GetConstellation = "獅子座" Else GetConstellation = "巨蟹座"
Case 8 : If d >= 23 Then GetConstellation = "處女座" Else GetConstellation = "獅子座"
Case 9 : If d >= 23 Then GetConstellation = "天秤座" Else GetConstellation = "處女座"
Case 10 : If d >= 24 Then GetConstellation = "天蠍座" Else GetConstellation = "天秤座"
Case 11 : If d >= 23 Then GetConstellation = "射手座" Else GetConstellation = "天蠍座"
Case 12 : If d >= 22 Then GetConstellation = "摩羯座" Else GetConstellation = "射手座"
Case Else: GetConstellation = "月份錯誤"
End Select
End Function
%>
<%
' 從表單/資料庫取得生日 (假設格式 YYYY-MM-DD)
Dim birthDate, monthDay, constellation
birthDate = Request.Form("birthday") ' 例:1990-01-26
If IsDate(birthDate) Then
' 轉為 MMDD
monthDay = Right("0" & Month(birthDate), 2) & Right("0" & Day(birthDate), 2)
constellation = GetConstellation(monthDay)
Response.Write "您的星座是:" & constellation
Else
Response.Write "請輸入有效日期 (YYYY-MM-DD)"
End If
%>
若輸入格式不固定,可參考《在 ASP 中進行時間格式格式化的方法》統一轉換為 YYYY-MM-DD 再提取月日。
// PHP 版
function getConstellation($month, $day) {
$bounds = [
[1,20,'水瓶座'], [2,19,'雙魚座'], [3,21,'白羊座'], [4,20,'金牛座'],
[5,21,'雙子座'], [6,22,'巨蟹座'], [7,23,'獅子座'], [8,23,'處女座'],
[9,23,'天秤座'], [10,24,'天蠍座'], [11,23,'射手座'], [12,22,'摩羯座']
];
foreach ($bounds as $b) {
if ($month > $b[0] || ($month == $b[0] && $day >= $b[1])) $zodiac = $b[2];
}
return $zodiac ?? '摩羯座'; // 12/22 之後
}
封裝為可複用函數/類別,配合單元測試覆蓋邊界日期 (如 1/19、1/20、2/18、2/19),確保邏輯正確無誤。