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     

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM