js时间格式化 Tue Apr 14 15:33:44 CST 2015 转成2015-04-14

2025-02-03 16:13:49
推荐回答(1个)
回答1:

第一种方法

    自定义函数

//date 是一个 Date实例

 format(date){

    return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDay();

}

第二种 

修改Date原形函数 因为Date的输出函数比较多 我们就拿toLocaleDateString()方法来重写

代码如下:

 Date.prototype.toLocaleDateString = function(DatePattern){       
  if(/yyyy.MM.dd/.test(DatePattern)){
        DatePattern = DatePattern.replace("yyyy",this.getFullYear()).replace("MM",this.getMonth()+1).replace("dd",this.getDay());
        return DatePattern;
        }
       return this.toLocaleString();
  };

这里你可以以一个时间格式作为参数:

   

var date = new Date();
var str = date.toLocaleDateString("yyyy-MM-dd");//返回值为格式化之后的日期

当然 并不能很全的格式化 ,这里也只是提供思路。