首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

JavaScript 日期字符串格式化提取:獲取年月、月日等自定義格式

     編輯:程式設計綜合問答

需求場景

輸入格式固定的日期時間字符串:"2015-06-05 16:21:40",需提取:

  • B = "2015-06"(年月)
  • C = "06-05"(月日)

方案一:原生 Date + 格式化原型(推薦)

// 擴展 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];

方案三:現代庫(Moment.js / Day.js / date-fns)

// 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
  • 時區問題:解析無時區字符串默認按本地時區,跨時區業務需明確指定 UTC
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved