萬盛學電腦網

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

JavaScript 日期格式化終極方案:Date.prototype.format 擴展詳解

核心代碼(掛載到 Date 原型)

Date.prototype.format = function(format) {
  var o = {
    "M+": this.getMonth() + 1,     // 月份
    "d+": this.getDate(),          // 日
    "h+": this.getHours(),         // 時(24制)
    "m+": this.getMinutes(),       // 分
    "s+": this.getSeconds(),       // 秒
    "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
    "S": this.getMilliseconds()    // 毫秒
  };

  // 年份特殊處理:yyyy / yy
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }

  // 其他字段:根據佔位符長度決定是否補零
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    }
  }
  return format;
};

使用示例

var now = new Date();

console.log(now.format("yyyy-MM-dd hh:mm:ss")); // 2024-01-15 14:30:05
console.log(now.format("yy-M-d h:m:s"));        // 24-1-15 14:30:5
console.log(now.format("yyyy年MM月dd日"));      // 2024年01月15日
console.log(now.format("q季度"));               // 1季度
console.log(now.format("S毫秒"));               // 123毫秒

格式化字符對照表

符號含義示例輸出
y年2024 / 24
M月1 / 01
d日5 / 05
h時(24制)9 / 09
m分3 / 03
s秒7 / 07
q季度1-4
S毫秒123

時間戳格式化

// 13位毫秒時間戳
var timestamp = 1705312205123;
console.log(new Date(timestamp).format("yyyy-MM-dd hh:mm:ss.S"));

// 10位秒時間戳
var timestampSec = 1705312205;
console.log(new Date(timestampSec * 1000).format("yyyy-MM-dd"));

現代替代: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/01/15 14:30:05"
copyright © 萬盛學電腦網 all rights reserved