輸入格式固定的日期時間字符串:"2015-06-05 16:21:40",需提取:
B = "2015-06"(年月)C = "06-05"(月日)// 擴展 Date 原型
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;
};
// 使用
var dateStr = "2015-06-05 16:21:40";
var date = new Date(dateStr.replace(/-/g, "/")); // 兼容 Safari
var B = date.format("yyyy-MM"); // "2015-06"
var C = date.format("MM-dd"); // "06-05"
console.log(B, C);
var str = "2015-06-05 16:21:40";
var B = str.match(/^(\d{4}-\d{2})/)[1]; // "2015-06"
var C = str.match(/^\d{4}-(\d{2}-\d{2})/)[1]; // "06-05"
// 或更通用
var parts = str.split(/[- :]/); // ["2015","06","05","16","21","40"]
var B = parts[0] + "-" + parts[1];
var C = parts[1] + "-" + parts[2];
// Day.js (2KB, 不可變, API 與 Moment 兼容)
import dayjs from 'dayjs';
var B = dayjs("2015-06-05 16:21:40").format("YYYY-MM");
var C = dayjs("2015-06-05 16:21:40").format("MM-DD");
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| 原型擴展 | 功能全、無依賴 | 污染原型、代碼較長 | 項目無構建工具、需多種格式 |
| 正則/分割 | 極簡、高性能 | 格式固定時有效 | 格式固定、僅需提取特定部分 |
| Day.js | 體積小、鏈式調用、TypeScript 支持 | 需構建工具 | 現代前端項目、需國際化/時區 |
new Date("2015-06-05") 在 Safari/舊瀏覽器可能解析失敗,統一用 replace(/-/g, "/")getMonth() 返回 0-11,輸出時需 +1