萬盛學電腦網

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

JavaScript 實現萬年曆:計算指定日期為當年第幾週與星期幾

計算某日期是當年的第幾週、星期幾,看似簡單卻暗藏閏年、週起始日定義、時區等陷阱。本文從零實作一個純 JS 萬年曆核心邏輯,涵蓋日期驗證、累積天數計算、週數判定(ISO 8601 vs 當地習慣)、星期映射,並提供完整互動式 HTML 介面。

核心邏輯:天數累積 + 週數計算

function getDateInfo(year, month, day) {
  // 1. 輸入驗證
  year = Number(year); month = Number(month); day = Number(day);
  if (isNaN(year) || year < 1) throw new Error('無效年份');
  if (month < 1 || month > 12) throw new Error('無效月份');
  
  // 2. 判斷閏年
  const isLeap = (y) => (y % 4 === 0 && y % 100 !== 0) || (y % 400 === 0);
  
  // 3. 每月天數表
  const monthDays = [31, isLeap(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  if (day < 1 || day > monthDays[month - 1]) throw new Error('無效日期');
  
  // 4. 計算當年第幾天 (1-based)
  let dayOfYear = day;
  for (let m = 1; m < month; m++) {
    dayOfYear += monthDays[m - 1];
  }
  
  // 5. 計算星期 (0=週日 ... 6=週六)
  const dateObj = new Date(year, month - 1, day);
  const weekDay = dateObj.getDay();
  const weekNames = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  
  // 6. 計算第幾週(兩種定義)
  // 定義 A:簡單除法 (1月1日所在週為第1週)
  const weekOfYearSimple = Math.ceil((dayOfYear + dateObj.getDay()) / 7);
  
  // 定義 B:ISO 8601 週數 (週一為週首,首週包含該年第一個週四)
  // 使用 Intl 或手動實現
  const isoWeek = getISOWeek(dateObj);
  
  return {
    year, month, day,
    dayOfYear,
    weekDay: weekNames[weekDay],
    weekOfYearSimple,
    isoWeek,
    isLeapYear: isLeap(year)
  };
}

// ISO 8601 週數計算
function getISOWeek(date) {
  const target = new Date(date.valueOf());
  const dayNr = (target.getDay() + 6) % 7; // 週一=0
  target.setDate(target.getDate() - dayNr + 3); // 移至該週週四
  const firstThursday = target.valueOf();
  target.setMonth(0, 1); // 1月1日
  if (target.getDay() !== 4) { // 若1月1日非週四
    target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7); // 移至第一個週四
  }
  return 1 + Math.ceil((firstThursday - target.valueOf()) / 604800000); // 7*24*3600*1000
}

完整互動式 HTML 介面

<!DOCTYPE html>
<html lang="zh-TW">
<head>
  <meta charset="UTF-8">
  <title>萬年曆 - 日期週數計算器</title>
  <style>
    body { font-family: sans-serif; max-width: 500px; margin: 2rem auto; padding: 0 1rem; }
    .form-group { margin: 1rem 0; display: flex; gap: 0.5rem; align-items: center; }
    label { min-width: 80px; }
    select, input { padding: 0.5rem; flex: 1; }
    button { padding: 0.75rem 1.5rem; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
    button:hover { background: #0056b3; }
    .result { margin-top: 1.5rem; padding: 1rem; background: #f8f9fa; border-radius: 4px; white-space: pre-line; }
    .error { color: #dc3545; }
  </style>
</head>
<body>
  <h1>📅 萬年曆查詢</h1>
  <div class="form-group">
    <label>年份:</label>
    <input type="number" id="year" value="2024" min="1" max="9999" />
  </div>
  <div class="form-group">
    <label>月份:</label>
    <select id="month">
      <script>for(let m=1;m<=12;m++) document.write(`<option value="${m}"${m===1?' selected':''}>${m}月</option>`);</script>
    </select>
  </div>
  <div class="form-group">
    <label>日期:</label>
    <select id="day"></select>
  </div>
  <button onclick="query()">查詢</button>
  <div id="result" class="result"></div>

  <script>
  // 動態更新日期選項
  function updateDays() {
    const y = +document.getElementById('year').value;
    const m = +document.getElementById('month').value;
    const isLeap = (y%4===0&&y%100!==0)||y%400===0;
    const days = [31, isLeap?29:28, 31,30,31,30,31,31,30,31,30,31][m-1];
    const daySel = document.getElementById('day');
    daySel.innerHTML = '';
    for(let d=1; d<=days; d++) daySel.add(new Option(d+'日', d));
  }
  document.getElementById('year').addEventListener('change', updateDays);
  document.getElementById('month').addEventListener('change', updateDays);
  updateDays();

  function query() {
    try {
      const y = +document.getElementById('year').value;
      const m = +document.getElementById('month').value;
      const d = +document.getElementById('day').value;
      const info = getDateInfo(y, m, d);
      document.getElementById('result').textContent = 
        `📅 ${info.year}年${info.month}月${info.day}日
📆 當年第 ${info.dayOfYear} 天
🗓️ 簡易週數: 第 ${info.weekOfYearSimple} 週
📐 ISO 8601 週數: 第 ${info.isoWeek} 週
📍 星期: ${info.weekDay}
${info.isLeapYear ? '🐸 閏年' : '平年'}`;
    } catch (e) {
      document.getElementById('result').innerHTML = `❌ ${e.message}`;
    }
  }
  </script>
</body>
</html>

關鍵陷阱與細節

陷阱說明解決
閏年判斷能被4整除但非百年,或被400整除(y%4===0&&y%100!==0)||y%400===0
月份 0-basednew Date 月份 0-11傳入 month-1
週數定義歧義美國/中文習慣 vs ISO 8601明確標註或提供兩種
時區影響new Date() 用本地時區純日期計算無影響,跨時區用 UTC
輸入型別表單值為字串統一 Number() 轉換

現代化替代:Temporal API (Stage 3)

// 未來標準 (目前需 Polyfill)
import { PlainDate } from '@js-temporal/polyfill';
const date = PlainDate.from({ year: 2024, month: 3, day: 15 });
console.log(date.dayOfWeek);      // 5 (週五,1=週一)
console.log(date.weekOfYear);     // ISO 週數
console.log(date.dayOfYear);      // 當年第幾天

日期計算是商務邏輯的高發區,建立可測試、可復用、文檔化的工具函數,能避免無數「上線後發現週數對不上」的血淚教訓。

copyright © 萬盛學電腦網 all rights reserved