各種時間格式轉換、時間戳轉換


1、后端接口返回時間格式轉換成時間戳

  例:2021-02-15T09:33:08.694+0000

  方案1:

    const time = 2021-02-15T09:33:08.694+0000

    時間戳:new Date(time).getTime()

  方案2: 安裝moment

    import moment from 'moment';

    const time = 2021-02-15T09:33:08.694+0000

    時間戳:moment(time).valueOf()

 
 2、后端返回時間格式轉換成 展示的時間狀態
 
  例如 2021-02-15T09:33:08.694+0000 =>2021-02-15 09:33:08
 
  方案1:安裝moment
    import moment from 'moment';

    const time = 2021-02-15T09:33:08.694+0000

    時間:moment(time).format('YYYY-MM-DD HH:mm:ss)   

  方案2:不展示

    使用正則表達式分別找到'T'、'.'的索引值,然后字符串的方式截取

3、時間戳展示成展示格式(2020-12-04 15:22:42)或者年月日

  可直接引用此函數

  getTsFormatDate(timeStamp) {
    var date = new Date(timeStamp);
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
 
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var seconds = date.getSeconds();

    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    if (hours >= 0 && hours <= 9) {
      hours = "0" + hours;
    }
    if (minutes >= 0 && minutes <= 9) {
      minutes = "0" + minutes;
    }
    if (seconds >= 0 && seconds <= 9) {
      seconds = "0" + seconds;
    }
    var currentdate = `${year}-${month}-${strDate} ${hours}:${minutes}:${seconds}`;
    //或年月日 (注意展示年月日的時候上面的month、strDate、hours、minutes、seconds可不做加0處理)
    //var currentdate = `${year}年${month}月${strDate}日 ${hours}時${minutes}分${seconds}秒`;
    return currentdate;
   }

4、擴展

 // 將當前時間換成時間格式字符串

var timestamp3 = 1403058804; var newDate = new Date(); newDate.setTime(timestamp3 * 1000); // Wed Jun 18 2014 console.log(newDate.toDateString()); // Wed, 18 Jun 2014 02:33:24 GMT console.log(newDate.toGMTString()); // 2014-06-18T02:33:24.000Z console.log(newDate.toISOString()); // 2014-06-18T02:33:24.000Z console.log(newDate.toJSON()); // 2014年6月18日 console.log(newDate.toLocaleDateString()); // 2014年6月18日 上午10:33:24 console.log(newDate.toLocaleString()); // 上午10:33:24 console.log(newDate.toLocaleTimeString()); // Wed Jun 18 2014 10:33:24 GMT+0800 (中國標准時間) console.log(newDate.toString()); // 10:33:24 GMT+0800 (中國標准時間) console.log(newDate.toTimeString()); // Wed, 18 Jun 2014 02:33:24 GMT console.log(newDate.toUTCString());




免責聲明!

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



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