将Date转换成 yyyy-MM-dd 格式的字符串

// 方法1 原型
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(),      //day
        "h+": this.getHours(),     //hour
        "m+": this.getMinutes(),   //minute
        "s+": this.getSeconds(),   //second
        "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
        "S": this.getMilliseconds() //millisecond
    }
    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 e = new Date();
var result1 = e.format('yyyy-MM-dd');
var result2 = e.format('yyyy-MM-dd hh:mm:ss');


// 方法2 函数
var dateFormat = function (d, format) {
    var o = {
    "M+" : d.getMonth()+1, //month
    "d+" : d.getDate(),    //day
    "h+" : d.getHours(),   //hour
    "m+" : d.getMinutes(), //minute
    "s+" : d.getSeconds(), //second
    "q+" : Math.floor((d.getMonth()+3)/3),  //quarter
    "S" : d.getMilliseconds() //millisecond
    };
    if(/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (d.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 e = new Date();
var result1 = dateFormat(e, 'yyyy-MM-dd');
var result2 = dateFormat(e, 'yyyy-MM-dd hh:mm:ss');
 
原文地址:https://www.cnblogs.com/james641/p/9266650.html