JavaScript 內建 Date 物件提供 getDay() 方法,回傳 0-6 代表星期日到星期六。本文示範如何取得當前星期並轉為中文顯示,附完整可執行範例。
const date = new Date();
const dayIndex = date.getDay(); // 0=星期日, 1=星期一, ..., 6=星期六
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>取得當前星期</title>
</head>
<body>
<p id="demo">點擊按鈕顯示今天星期</p>
<button onclick="showWeekday()">顯示星期</button>
<script>
function showWeekday() {
const d = new Date();
const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
const today = weekdays[d.getDay()];
document.getElementById('demo').innerHTML = `今天是 ${today}`;
}
</script>
</body>
</html>
// 2024 年 1 月 1 日
const specific = new Date(2024, 0, 1); // 月份 0 基礎
console.log(['日','一','二','三','四','五','六'][specific.getDay()]); // "一"
function isWeekend(date = new Date()) {
const day = date.getDay();
return day === 0 || day === 6;
}
console.log(isWeekend()); // 視今天而定
function nextWorkday(date = new Date()) {
const d = new Date(date);
do {
d.setDate(d.getDate() + 1);
} while (d.getDay() === 0 || d.getDay() === 6);
return d;
}
getDay() 回傳星期索引,getDate() 回傳月份日期 (1-31)。new Date() 使用瀏覽器本地時區,跨時區應用請考慮 UTC 方法。| 方法 | 說明 | 回傳範例 |
|---|---|---|
| getDay() | 星期索引 | 0-6 |
| getDate() | 月份日期 | 1-31 |
| getMonth() | 月份索引 | 0-11 |
| getFullYear() | 完整年份 | 2024 |
| toLocaleDateString() | 本地化日期字串 | "2024/1/15" |
善用 getDay() 搭配對應陣列即可輕鬆顯示中文星期。結合 Date 物件其他方法,可構建行事曆、排程判斷、週末邏輯等實用功能。