时间戳转换日期格式

时间戳转换日期格式

什么是时间戳

Unix时间戳(Unix timestamp),或称Unix时间(Unix time)、POSIX时间(POSIX time),是一种时间表示方式,定义为从格林威治时间1970年01月01日00时00分00秒起至现在的总秒数。

10位时间戳和13位时间戳的区别

date默认精度是毫秒,也就是说生成的时间戳就是13位的,有的时间戳默认就是10位的,因为其精度是秒。

时间戳转换日期格式

// 时间戳转换
    formatLinuxTime(data){
        if (data) {
            let time = this.timestampToTime(data);
            return time
        }
        return '';
    },
    timestampToTime(timestamp) {
      var date = new Date(timestamp); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
      Y = date.getFullYear() + '-';
      M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      D = date.getDate() < 10 ? '0' + (date.getDate()) + ' ' : date.getDate() + ' ';
      h = date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':';
      m = date.getMinutes() < 10 ? '0' + date.getMinutes() + ':' : date.getMinutes() + ':';
      s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },
    console.log(this.formatLinuxTime(1615361100000))

在这里插入图片描述
注意formatLinuxTime方法传值必须为number类型,字符串会转换成NaN-NaN-NaN NaN:NaN:NaN

时间转换成时间戳

  1. js获取当前时间戳的方法
var timestamp1 = Date.parse(new Date());
var timestamp2 = (new Date()).valueOf();
var timestamp3 = new Date().getTime();
  1. js获取制定时间戳的方法
var oldTime = (new Date("2021/03/10 15:25:00")).getTime()
//返回数值的单位是毫秒。

gmt转time

transDate(data) {
      if (data) {
        function renderTime(date) {
          var dateee = new Date(date).toJSON();
          return new Date(+new Date(dateee) + 8 * 3600 * 1000)
            .toISOString()
            .replace(/T/g, " ")
            .replace(/\.[\d]{3}Z/, "");
        }
        let time = renderTime(data);
        return time;
      }
      return "";
    },

猜你喜欢

转载自blog.csdn.net/weixin_43881166/article/details/114637828