萬盛學電腦網

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

JavaScript Date Mask 日期格式化解析器:字串轉標準 YYYY/MM/DD

前言

專案常需解析各種格式的日期字串(如 `dd-mmm-yy`, `MM/DD/YYYY`)轉為標準 `YYYY/MM/DD`。本文提供一個健全的 `StringToDate` 函式,支援月份名稱、星期名稱、雙位數年份切斷點等複雜格式。

核心函式:StringToDate(sDate, sFormat, cutOff)

const MonthNames = ['January','February','March','April','May','June',
  'July','August','September','October','November','December'];
const ShortMths = ['Jan','Feb','Mar','Apr','May','Jun',
  'Jul','Aug','Sep','Oct','Nov','Dec'];
const DayNames = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
const ShortDays = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];

function StringToDate(sDate, sFormat, cutOff) {
  // 1. 統一大寫
  sDate = sDate.toString().toUpperCase();
  sFormat = sFormat.toUpperCase();

  // 2. 月份名稱轉數字 (MMM/MMMM -> MM)
  if (sFormat.match(/MMMM|MMM/)) {
    sDate = sDate.replace(new RegExp('(' + ShortMths.join('|') + ')[A-Z]*', 'gi'), m => {
      const i = ShortMths.indexOf(m.charAt(0).toUpperCase() + m.substr(1,2).toLowerCase()) + 1;
      return (i < 10 ? '0' : '') + i;
    });
    sFormat = sFormat.replace(/MMMM|MMM/g, 'MM');
  }

  // 3. 移除星期名稱
  if (sFormat.match(/DDDD|DDD/)) {
    sDate = sDate.replace(new RegExp('(' + ShortDays.join('|') + ')[A-Z]*', 'gi'), '');
    sFormat = sFormat.replace(/DDDD|DDD/g, '');
  }

  // 4. 單位數補零 (D/M -> DD/MM)
  sDate = sDate.replace(/(^|[^DMY])(D|M)(?=[^DMY]|$)/g, '$1$2$2');
  sFormat = sFormat.replace(/(^|[^DMY])(D|M)(?=[^DMY]|$)/g, '$1$2$2');

  // 5. 檢查單一 D/M (如 DMM, MDD 等非法格式)
  if (sFormat.search(/(^|[^D])D([^D]|$)|(^|[^M])M([^M]|$)/) + 1) return '';

  // 6. 雙位年份處理 (YY -> YYYY)
  sFormat = sFormat.replace(/(^|[^Y])(YY)(?=[^Y]|$)/g, ($0, $1, $2, idx) => {
    const yearPart = sDate.substr(idx + 1, 2);
    const prefix = (cutOff !== undefined && parseInt(yearPart,10) > cutOff) ? '19' : '20';
    sDate = sDate.substr(0, idx+1) + prefix + sDate.substr(idx+1);
    return $1 + $2 + $2;
  });

  // 7. 組裝 YYYY/MM/DD
  let sParsed = 'YYYY/MM/DD'.replace(/YYYY|MM|DD/g, m => {
    const pos = sFormat.indexOf(m);
    return pos >= 0 ? sDate.substr(pos, m.length) : '';
  });

  // 8. 補齊缺失年/日
  if (sParsed.startsWith('/')) sParsed = new Date().getFullYear() + sParsed;
  if (sParsed.endsWith('/')) sParsed += '01';

  return sParsed.length === 10 ? sParsed : '';
}

使用範例

<script>
console.log(StringToDate('15-Jan-24', 'DD-MMM-YY', 30)); // "2024/01/15"
console.log(StringToDate('January 15, 2024', 'MMMM DD, YYYY')); // "2024/01/15"
console.log(StringToDate('Mon, Jan 15', 'DDD, MMM DD')); // "2024/01/15" (年份預設今年)
console.log(StringToDate('99', 'YY', 50)); // "1999" (cutOff=50, 99>50 -> 1999)
console.log(StringToDate('40', 'YY', 50)); // "2040" (40<=50 -> 2040)
</script>

現代替代方案

  • date-fns:`parse(str, 'dd-MMM-yy', new Date())`,模組化、Tree-shakable。
  • Luxon:`DateTime.fromFormat(str, 'dd-MMM-yy')`,不可變、Intl 為基礎。
  • 原生:`new Date(str)` 配合 `toISOString().slice(0,10)`,但格式容錯度低。

總結

`StringToDate` 展示了日期解析的核心邏輯:正規化 → 標記替換 → 零補齊 → 年份展開 → 組裝。現代專案建議引入成熟日期庫,避免自行維護解析器。

copyright © 萬盛學電腦網 all rights reserved