萬盛學電腦網

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

JavaScript 日期範圍初始化:取得「上個月同日」的零時區安全寫法

常見錯誤:`setMonth(getMonth()-1)` 的陷阱

// ❌ 危險:3/31 → 2/31 不存在 → 自動變 3/3 或 3/2 (視瀏覽器)
const d = new Date('2024-03-31');
d.setMonth(d.getMonth() - 1);
console.log(d); // 2024-03-02 或 2024-03-03 ❌

原因:`setMonth` 會保留原日期數,若目標月份天數不足會**自動向後推算**,導致邏輯錯誤。

正確做法:先設為「當月 1 號」,再減 1 個月,最後設回目標日期

/**
 * 取得指定日期的「上個月同日」,若上個月無該日則取「上個月最後一天」
 * @param {Date} date - 基準日期(預設今天)
 * @returns {Date} 新 Date 物件(不修改原物件)
 */
function getSameDayLastMonth(date = new Date()) {
  const d = new Date(date); // 複製,避免副作用
  d.setDate(1);             // 1. 先鎖定當月 1 號(永遠存在)
  d.setMonth(d.getMonth() - 1); // 2. 安全減 1 月
  // 3. 嘗試設回原日期,若超過該月天數會自動變成下個月 1 號
  const targetDate = date.getDate();
  d.setDate(targetDate);
  // 4. 若月份變了(如 3/31 → 4/1),退回上個月最後一天
  if (d.getMonth() !== (date.getMonth() - 1 + 12) % 12) {
    d.setDate(0); // 0 代表上個月最後一天
  }
  return d;
}

// 測試
console.log(getSameDayLastMonth(new Date('2024-03-31')).toISOString().split('T')[0]); // 2024-02-29 ✅
console.log(getSameDayLastMonth(new Date('2024-05-15')).toISOString().split('T')[0]); // 2024-04-15 ✅
console.log(getSameDayLastMonth(new Date('2024-01-31')).toISOString().split('T')[0]); // 2023-12-31 ✅

完整「日期範圍初始化」元件(含格式化、時區安全、jQuery/原生雙版)

ES6 模組版(推薦)

// dateRange.js
export function formatDate(date, fmt = 'YYYY-MM-DD') {
  const pad = n => String(n).padStart(2, '0');
  return fmt
    .replace('YYYY', date.getFullYear())
    .replace('MM', pad(date.getMonth() + 1))
    .replace('DD', pad(date.getDate()));
}

export function getDefaultRange() {
  const end = new Date(); // 今天 00:00:00 本地時間
  end.setHours(0,0,0,0);
  const start = getSameDayLastMonth(end);
  return { start, end };
}

function getSameDayLastMonth(d) { /* 同上 */ }

// 使用
import { getDefaultRange, formatDate } from './dateRange.js';
const { start, end } = getDefaultRange();
document.getElementById('txtBegin').value = formatDate(start);
document.getElementById('txtEnd').value   = formatDate(end);

零依賴瀏覽器直用版

<input type="date" id="txtBegin"> ~ <input type="date" id="txtEnd">

<script>
(function() {
  function pad(n){ return String(n).padStart(2,'0'); }
  function fmt(d){ return d.getFullYear()+'-'+pad(d.getMonth()+1)+'-'+pad(d.getDate()); }
  function sameDayLastMonth(d){
    const nd = new Date(d); nd.setDate(1); nd.setMonth(nd.getMonth()-1);
    nd.setDate(d.getDate());
    if (nd.getMonth() !== (d.getMonth()-1+12)%12) nd.setDate(0);
    return nd;
  }
  const end = new Date(); end.setHours(0,0,0,0);
  const start = sameDayLastMonth(end);
  document.getElementById('txtBegin').value = fmt(start);
  document.getElementById('txtEnd').value   = fmt(end);
})();
</script>

時區與夏令時陷阱

  • `new Date()` 產生**本地時間**,`getMonth()`/`getDate()` 皆為本地曆法,適合表單 ``(同樣用本地曆)。
  • 若後端要求 UTC,請用 `toISOString().split('T')[0]` 或 `date.getUTCFullYear()` 等 UTC 方法。
  • 跨夏令時切換日(如 3 月第 2 個週日)仍以「曆日」計算,不受小時漂移影響。

擴展:任意月份偏移工具函數

/**
 * @param {Date} date
 * @param {number} monthsOffset 正數=未來,負數=過去
 * @param {boolean} clampToMonthEnd 若目標月無該日,是否夾到月底(預設 true)
 */
function addMonths(date, monthsOffset, clampToMonthEnd = true) {
  const d = new Date(date);
  const targetDate = d.getDate();
  d.setDate(1);
  d.setMonth(d.getMonth() + monthsOffset);
  if (clampToMonthEnd) {
    d.setDate(targetDate);
    if (d.getDate() !== targetDate) d.setDate(0); // 回滾到月底
  } else {
    d.setDate(Math.min(targetDate, new Date(d.getFullYear(), d.getMonth()+1, 0).getDate()));
  }
  return d;
}

結語

日期運算看似簡單,實則暗藏「月份天數不固定、夏令時、時區」三大坑。掌握 **「先設 1 號 → 加減月 → 設回目標日 → 修正溢位」** 核心模式,即可安全處理所有「同月同日」與「月末」邊界情況,避免生產環境出現 2 月 30 日、3 月 31 日跳變等低級 Bug。

copyright © 萬盛學電腦網 all rights reserved