时间控件格式化,有了他,我再也不怕格式化时间了

以前最怕前台格式化时间,所以从网上查找资料,整理了一个日期格式化控件,非常好用。 

1.直接上代码,引入到自己的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(), //cond
        "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;
    } 

2.使用非常简单,举两个例子。

2.1 new Date().format("yyyy-MM-dd");// 可以格式化成如:2015-09-20的形式

2.2 new Date("2015920").format("yyyy-MM-dd"); //同上

从此,再也不怕前台的日期转换了。

 

原文地址:https://www.cnblogs.com/sloveling/p/date_format.html