用JavaScript(js)对时间格式化

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 d =new Date().format('yyyy-MM-dd');

另一种方法:

在Javascript之中,日期对象是Date,那么如何将一个日期对象按照定制的格式进行输出呢? 
  可以现告诉你,Date对象有有四个内置方法,用于输出为字符串格式,分别为: 
  1)toGMTString,将一个日期按照GMT格式显示 
  2)toLocaleString,将一个日期按照本地操作系统格式显示 
  3)toLocaleDateString,按照本地格式显示一个日期对象的日期部分 
  4)toLocaleTimeString,按照本地格式显示一个日期对象的时间部分 

原文地址:https://www.cnblogs.com/xuan52rock/p/4718013.html