萬盛學電腦網

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

JavaScript 日期比較大小:正確姿勢與常見陷阱避坑指南

核心原則

日期比較必須轉為時間戳(毫秒數)或 Date 對象直接比較,絕不可直接比較字符串。

正確比較方式

1. Date 對象直接比較(推薦)


const d1 = new Date('2024-01-15');
const d2 = new Date('2024-01-20');

d1 < d2;  // true
d1 > d2;  // false
d1 <= d2; // true
d1.getTime() < d2.getTime(); // 等價,更明確

2. 字符串比較(僅限 ISO 8601 格式 YYYY-MM-DD)


// ✅ 安全:ISO 格式字符串按字典序等同於時間序
'2024-01-15' < '2024-01-20'; // true
'2024-01-15T14:30:00' < '2024-01-15T15:00:00'; // true

// ❌ 危險:其他格式字符串比較不可靠
'01/15/2024' < '01/20/2024'; // true (美式碰巧對)
'15-01-2024' < '20-01-2024'; // false! 字典序 '2' > '1'

解析字符串為 Date 的標準化


/**
 * 安全解析日期字符串為 Date 對象
 * @param {string} str - 支持 'YYYY-MM-DD', 'YYYY/MM/DD', 'YYYY.MM.DD', 時間戳
 * @returns {Date|null}
 */
function parseDate(str) {
  if (!str) return null;
  // 統一分隔符為 / (Safari 不支持 YYYY-MM-DD)
  const normalized = str.replace(/[-.]/g, '/');
  const date = new Date(normalized);
  return isNaN(date.getTime()) ? null : date;
}

// 使用
const d1 = parseDate('2024-01-15');
const d2 = parseDate('2024/01/20');
const d3 = parseDate('1705300245123'); // 時間戳
if (d1 && d2 && d1 < d2) { /* ... */ }

完整比較工具函數


const DateCompare = {
  /**
   * 比較兩個日期
   * @returns -1: d1d2, NaN: 無效日期
   */
  compare(d1, d2) {
    const t1 = this.toTimestamp(d1);
    const t2 = this.toTimestamp(d2);
    if (isNaN(t1) || isNaN(t2)) return NaN;
    return t1 < t2 ? -1 : t1 > t2 ? 1 : 0;
  },
  
  toTimestamp(val) {
    if (val instanceof Date) return val.getTime();
    if (typeof val === 'number') return val;
    if (typeof val === 'string') return this.parseDate(val)?.getTime();
    return NaN;
  },
  
  parseDate(str) {
    if (!str) return null;
    const normalized = str.replace(/[-.]/g, '/');
    const date = new Date(normalized);
    return isNaN(date.getTime()) ? null : date;
  },
  
  // 只比較日期部分(忽略時間)
  compareDateOnly(d1, d2) {
    const toDateOnly = (d) => new Date(d).setHours(0,0,0,0);
    return this.compare(toDateOnly(d1), toDateOnly(d2));
  },
  
  // 檢查是否在範圍內
  isBetween(date, start, end, inclusive = true) {
    const t = this.toTimestamp(date);
    const s = this.toTimestamp(start);
    const e = this.toTimestamp(end);
    if ([t,s,e].some(isNaN)) return false;
    return inclusive ? t >= s && t <= e : t > s && t < e;
  },
  
  // 是否為今天
  isToday(date) {
    return this.compareDateOnly(date, new Date()) === 0;
  },
  
  // 是否過期
  isPast(date) {
    return this.compare(date, new Date()) < 0;
  }
};

// 使用
DateCompare.compare('2024-01-15', '2024-01-20'); // -1
DateCompare.compareDateOnly('2024-01-15 23:59', '2024-01-16 00:01'); // -1 (同天視為相等)
DateCompare.isBetween('2024-01-15', '2024-01-01', '2024-01-31'); // true

表單驗證實戰:開始/結束時間


function validateDateRange(startId, endId) {
  const startVal = document.getElementById(startId).value;
  const endVal = document.getElementById(endId).value;
  
  if (!startVal || !endVal) return { valid: true }; // 不強制填寫
  
  const start = DateCompare.parseDate(startVal);
  const end = DateCompare.parseDate(endVal);
  
  if (!start || !end) return { valid: false, msg: '日期格式無效' };
  
  // 允許同天
  if (DateCompare.compare(start, end) > 0) {
    return { valid: false, msg: '開始時間不能晚於結束時間' };
  }
  
  // 可選:限制最大跨度
  if (DateCompare.diffDays(start, end) > 365) {
    return { valid: false, msg: '時間跨度不能超過 1 年' };
  }
  
  return { valid: true };
}

// 綁定
$('#startTime, #endTime').on('change', function() {
  const result = validateDateRange('startTime', 'endTime');
  $('#time-error').toggle(!result.valid).text(result.msg || '');
});

常見陷阱總結

陷阱錯誤代碼正確代碼原因
直接比較字符串'2024-01-15' > '2024-01-20'new Date('2024-01-15') > new Date('2024-01-20')字典序≠時間序(非ISO格式)
new Date('YYYY-MM-DD') Safari 解析為 UTCnew Date('2024-01-15')new Date('2024/01/15') 或 parseDate()ECMA 規範:無時區標譽視為 UTC
忽略時間部分d1 < d2 (含時間)compareDateOnly(d1, d2)同天不同時刻會誤判
夏令時導致一天非 24hdate.getTime() + 86400000date.setDate(date.getDate()+1)DST 切換日 23/25 小時
無效日期不報錯new Date('invalid') < new Date()isNaN(date.getTime()) 先校驗Invalid Date 比較結果總為 false

現代庫推薦

  • date-fns: compareAsc(date1, date2), isBefore, isAfter, areIntervalsOverlapping
  • dayjs: dayjs(d1).isBefore(d2), .isSame(d2, 'day')
  • Luxon: DateTime.fromISO(d1) < DateTime.fromISO(d2)
copyright © 萬盛學電腦網 all rights reserved