各种时间格式转换、时间戳转换


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