JavaScript修改日期格式

<script>
  //封装时间格式
  function format(time, format) {
    var t = new Date(time);
    var tf = function (i) {
      return (i < 10 ? '0' : '') + i
    };
    return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
      switch (a) {
        case 'yyyy':
          return tf(t.getFullYear());
          break;
        case 'MM':
          return tf(t.getMonth() + 1);
          break;
        case 'mm':
          return tf(t.getMinutes());
          break;
        case 'dd':
          return tf(t.getDate());
          break;
        case 'HH':
          return tf(t.getHours());
          break;
        case 'ss':
          return tf(t.getSeconds());
          break;
      }
    })
  }
</script>
 1 //引用
 2           var getDate1=new Date();
 3           console.log(getDate1);    //输出Mon Oct 30 2017 14:33:20 GMT+0800 (中国标准时间)
 4          var result1=format(getDate1,'yyyy-MM-dd');
 5           console.log(result1);            //输出2017-10-30
 6 
 7 
 8           var getDate2=new Date().toLocaleDateString();
 9           console.log(getDate2);    //输出2017/10/30
10           var result2=format(getDate2,'yyyy-MM-dd');
11           console.log(result2);            //输出2017-10-30
12 
13     
原文地址:https://www.cnblogs.com/nelsonlei/p/7698583.html