萬盛學電腦網

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

JavaScript 將「中國標準時間」字串格式化為標準日期格式

輸入格式示例

Thu Aug 22 2013 15:12:00 GMT+0800 (中國標準時間)

此為 Date.toString() 在中文環境下的輸出,非標準 ISO 8601,不可直接用 new Date(str) 可靠解析(各瀏覽器行為不一)。

推薦方案:直接操作 Date 對象

若已有 Date 實例(如 new Date()、后端傳時間戳),直接格式化:

/**
 * 格式化 Date 為 YYYY-MM-DD HH:mm:ss
 * @param {Date} date
 * @returns {string}
 */
function formatDateTime(date) {
    if (!(date instanceof Date) || isNaN(date)) return '';
    var pad = function(n) { return n < 10 ? '0' + n : '' + n; };
    return date.getFullYear() + '-'
         + pad(date.getMonth() + 1) + '-'
         + pad(date.getDate()) + ' '
         + pad(date.getHours()) + ':'
         + pad(date.getMinutes()) + ':'
         + pad(date.getSeconds());
}

// 用法
var now = new Date(); // 或 new Date(timestamp)
console.log(formatDateTime(now)); // 2024-05-18 14:30:05

若必須解析字串:正則提取關鍵字段

function parseChineseDateStr(str) {
    // 匹配 "Thu Aug 22 2013 15:12:00 GMT+0800"
    var m = str.match(/(\w{3})\s+(\w{3})\s+(\d{1,2})\s+(\d{4})\s+(\d{2}:\d{2}:\d{2})/);
    if (!m) return null;
    var monthMap = {Jan:0,Feb:1,Mar:2,Apr:3,May:4,Jun:5,Jul:6,Aug:7,Sep:8,Oct:9,Nov:10,Dec:11};
    return new Date(m[4], monthMap[m[2]], m[3], ...m[5].split(':'));
}

警告:依賴語言環境的月份/星期縮寫極不穩健,**強烈建議後端直接傳 ISO 8601 (2013-08-22T15:12:00+08:00) 或時間戳**。

常用格式化模式封裝

Date.prototype.format = function(fmt) {
    var o = {
        'M+': this.getMonth() + 1,
        'd+': this.getDate(),
        'h+': this.getHours(),
        'm+': this.getMinutes(),
        's+': this.getSeconds(),
        'q+': Math.floor((this.getMonth() + 3) / 3),
        'S': this.getMilliseconds()
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    for (var k in o) if (new RegExp('(' + k + ')').test(fmt))
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
    return fmt;
};

// 用法
new Date().format('yyyy-MM-dd hh:mm:ss.S'); // 2024-05-18 14:30:05.123
new Date().format('yyyy/MM/dd');            // 2024/05/18

現代最佳實踐

  • Intl.DateTimeFormat:零依賴、本地化、可配置時區、格式選項豐富。
new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit',
    hour12: false
}).format(new Date()); // "2024/05/18 14:30:05"
  • date-fns / dayjs / Luxon:功能豐富、Tree-shakable、TypeScript 支援佳的輕量庫。
  • 後端統一輸出 ISO 8601 + 時區,前端僅做展示格式化,不做解析。
  • 拒絕解析非標準字串,源頭治理日期格式,是前後端協作的專業素養。

    copyright © 萬盛學電腦網 all rights reserved