DIV CSS 佈局教程網

JavaScript 以 Date-Mask 把日期物件轉為字串的實作解析
編輯:關於JavaScript     

日期格式化幾乎每個專案都躲不掉。下面這段經典的 StringToDate 函式,示範了如何用「格式遮罩」(format mask)的概念,把 dd-mmm-yy 這類描述字串與實際日期值對齊,最終輸出成 YYYY/MM/DD。

先準備好名稱對照表

英文月份與星期的全稱、簡稱都得先列出來,後續才能把 March、Mar 一律正規化成數字月份:

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

函式本體

var StringToDate = function (sDate, sFormat, cutOff) {
    // Input:  日期字串 sDate、格式字串 sFormat(例如 'dd-mmm-yy')
    //          cutOff 為可選的兩位數年份判斷門檻
    // 若格式中完全沒有 'd',視為該月 1 號
    // 若年份為 20、cutOff 為 30,則補成 2020;年份為 40 則補成 1940
    // 未提供 cutOff 時,一律在前面補 '20'
    // Output: 'YYYY/MM/DD' 或空字串
    // 註:DMM、MDD、DDM、YYYYD 這類無法判讀的組合會直接放棄解析
    var sParsed, fndSingle;

    // sParsed 最終會組出 'YYYY/MM/DD'
    sDate = sDate.toString().toUpperCase();
    sFormat = sFormat.toUpperCase();

    if (sFormat.search(/MMMM|MMM/) + 1) {
        // 把 Mar / March 換成 03
        sDate = sDate.replace(new RegExp('(' + ShortMths.join('|') + ')[A-Z]*', 'gi'), function (m) {
            var i = ShortMths.indexOf(m.charAt(0).toUpperCase() + m.substr(1, 2).toLowerCase()) + 1;
            return ((i < 10) ? "0" + i : "" + i).toString();
        });
        sFormat = sFormat.replace(/MMMM|MMM/g, 'MM');
    }

    if (sFormat.search(/DDDD|DDD/) + 1) {
        // 把 Tue / Tuesday 直接抹掉
        sDate = sDate.replace(new RegExp('(' + ShortDays.join('|') + ')[A-Z]*', 'gi'), '');
        sFormat = sFormat.replace(/DDDD|DDD/g, '');
    }

    // 個位數補零:2 → 02
    sDate = sDate.replace(/(^|\D)(\d)(?=\D|$)/g, function ($0, $1, $2) {
        return $1 + '0' + $2;
    });

    // 格式中的 D / M 也補成 DD / MM
    sFormat = sFormat.replace(/(^|[^DMY])(D|M)(?=[^DMY]|$)/g, function ($0, $1, $2) {
        return $1 + $2 + $2;
    });

    // 若仍殘留單獨的 D 或 M,代表格式無法解析(例如 'DMM')
    fndSingle = sFormat.search(/(^|[^D])D([^D]|$)|(^|[^M])M([^M]|$)/) + 1;
    if (fndSingle) return '';

    // 處理兩位數年份
    sFormat = sFormat.replace(/(^|[^Y])(YY)(?=[^Y]|$)/g, function ($0, $1, $2, index) {
        var tempDate = sDate.substr(0, index + 1);
        tempDate += (cutOff)
            ? ((parseInt(sDate.substr(index + 1, 2), 10) > cutOff) ? '19' : '20')
            : '20';
        tempDate += sDate.substr(index + 1);
        sDate = tempDate;
        return $1 + $2 + $2;
    });

    // 依格式位置把值取出來拼成 YYYY/MM/DD
    sParsed = ('YYYY/MM/DD').replace(/YYYY|MM|DD/g, function (m) {
        return (sFormat.indexOf(m) + 1) ? sDate.substr(sFormat.indexOf(m), m.length) : '';
    });

    // 沒寫年份就補當年
    if (sParsed.charAt(0) == '/') {
        sParsed = (new Date().getFullYear()) + sParsed;
    }
    // 沒寫日期就補 1 號
    if (sParsed.charAt(sParsed.length - 1) == '/') {
        sParsed += '01';
    }

    // 正常結果應為 10 個字元
    return (sParsed.length == 10) ? sParsed : '';
};

使用時機

這個寫法在需要「寬容解析」使用者輸入的舊系統中很常見:使用者可能輸入 5 Mar 2024,也可能輸入 03/05/24,只要格式遮罩寫對,都能收斂成同一個標準字串。若你今天是在新專案中使用,直接採用 Date 搭配 toISOString(),或引入 date-fns、Day.js 等函式庫,會更省心。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved