Js格式化时间函数 Date.prototype.format

拓展Date属性的时间格式化函数

知兮丶青 格式化 · 函数
阅读(3423) 2017-11-27
Js格式化时间函数 Date.prototype.format
Js格式化时间函数 Date.prototype.format

收藏个Javascript,拓展Date属性的时间格式化函数:Date.prototype.format。出处已经无从追溯。感谢广大分享者。我自己也收藏,方便以后用。


函数

/**
 * 格式化时间函数
 * @param {format} 时间显示格式
 */
Date.prototype.format = function (format) {
    var date = {
        "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+)/i.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
        }
    }
    return format;
};


用法

//使用方法
var now = new Date();

var year = now.format("yyyy");
console.log(year);
var month = now.format("MM");
console.log(month);
var day = now.format("dd");
console.log(day);

var date = now.format("yyyy-MM-dd");
console.log(date);
var date_1 = now.format("yyyy/MM/dd");
console.log(date_1);
var date_2 = now.format("yyyyMMdd");
console.log(date_2);

var date_time = now.format("yyyy-MM-dd hh:mm:ss");
console.log(date_time);
var date_time_1 = now.format("yyyy年MM月dd日 hh时mm分ss秒");
console.log(date_time_1);
var date_time_2 = now.format("yyyy-MM-dd hh:mm:ss.S");
console.log(date_time_2);

var simple_time = now.format("yyyy-M-d h:m:s.S");
console.log(simple_time);


输出

2017
11
26

2017-11-26
2017/11/26
20171126

2017-11-26 23:47:04
2017年11月26日 23时47分04秒
2017-11-26 23:47:04.175

2017-11-26 23:47:4.175


原创文章,转载请注明出处:https://www.weizhixi.com/article/6.html