專案常需解析各種格式的日期字串(如 `dd-mmm-yy`, `MM/DD/YYYY`)轉為標準 `YYYY/MM/DD`。本文提供一個健全的 `StringToDate` 函式,支援月份名稱、星期名稱、雙位數年份切斷點等複雜格式。
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>
`StringToDate` 展示了日期解析的核心邏輯:正規化 → 標記替換 → 零補齊 → 年份展開 → 組裝。現代專案建議引入成熟日期庫,避免自行維護解析器。