扩展JS内置Date对象,将时间转化为指定格式的字符串

233 阅读1分钟

对JS内置的Date对象进行扩展,可以将 Date 转化为指定格式的字符串

Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //月份           
        "d+": this.getDate(), //日           
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时           
        "H+": this.getHours(), //小时           
        "m+": this.getMinutes(), //分           
        "s+": this.getSeconds(), //秒           
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度           
        "S": this.getMilliseconds() //毫秒           
    };
    var week = {
        "0": "\u65e5",
        "1": "\u4e00",
        "2": "\u4e8c",
        "3": "\u4e09",
        "4": "\u56db",
        "5": "\u4e94",
        "6": "\u516d"
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(format)) {
        format = format.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[this.getDay() + ""]);
    }
    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;
}

格式字符串占位符

y:年。1~4 位占位符
M:月。1~2 位占位符
d:日。1~2 位占位符
h:小时(12制)。1~2 位占位符
H:小时(24制)。1~2 位占位符
m:分钟。1~2 位占位符
s:秒。1~2 位占位符
S:毫秒。1个占位符(是 1-3 位的数字)
E:周。1~3 位占位符
q:季度。1~2 位占位符

使用示例

  (new Date()).format("yyyy年MM月dd日,12小时制时间 hh小时mm分钟ss秒S毫秒,EEE,第 q 季度")
  //2021年06月16日,12小时制时间 10小时03分钟06秒714毫秒,星期三,第 2 季度
(new Date()).format("yyyy年MM月dd日,24小时制时间 HH小时mm分钟ss秒S毫秒,EEE,第 q 季度")
//2021年06月16日,24小时制时间 10小时04分钟46秒679毫秒,星期三,第 2 季度