把时间戳转为常用日期格式

时间戳理解了之后学着就不会太难,但是我总是觉得复杂,所以就不想去弄懂它,

但是时间戳的使用越来越广泛,我才认识到我得搞懂它,希望大家一起学习

首先先说一些Date对象的方法

    var a = new Date().toDateString();
    console.log(a); // Tue Jun 23 2020
var a = new Date().toISOString(); console.log(a); //2020-06-23T07:24:22.245Z
var a = new Date().toJSON(); console.log(a); //2020-06-23T07:26:01.812Z
var a = new Date().toLocaleDateString(); console.log(a); //2020/6/23
var a = new Date().toLocaleTimeString(); console.log(a); //下午3:30:12
var a = new Date().toLocaleString(); console.log(a); //2020/6/28 下午8:50:46
var a = new Date().toString(); console.log(a); //Sun Jun 28 2020 20:52:24 GMT+0800 (中国标准时间)
var a = new Date().toTimeString(); console.log(a); //20:53:49 GMT+0800 (中国标准时间)
var a = new Date().toUTCString(); console.log(a); //Sun, 28 Jun 2020 12:54:40 GMT

  

如果你想把时间戳转为2020/6/28 20:58:16格式

如何做的呢?

下面我们来说这种最近使用的方法

代码操作如下:

1.首先在vue组件中的data中声明一个有许多时间戳的数组

 data() {
    return {
      time: ["1592223461", "1592223031", "1592222732", "1592215722"]
    };
  },

2.在vue组件中的mounted中获取并转为常用日期格式

 mounted() {
    this.time.forEach(e => {
      var a = new Date(e * 1000); //为了补0的个数 时间戳为10位的话需*1000,时间戳为13位就不用*1000
      //  console.log(a)
      var year = a.getFullYear();      //getFullYear是从Date 对象以四位数字返回年份。
      var month = a.getMonth() + 1;   //getMonth从Date对象返回月份(0-11)   +1得到当前月份
      var data = a.getDate();         // getDate从 Date 对象返回一个月中的某一天 (1 ~ 31)
      var hour = a.getHours() + 1;    //getHours返回 Date 对象的小时 (0 ~ 23)。   +1得到当前小时 
      var min = a.getMinutes() + 1;   //getMinutes返回 Date 对象的分钟 (0 ~ 59)。 +1得到当前分钟数
      var sec = a.getSeconds() + 1;   //getSeconds返回 Date 对象的秒数 (0 ~ 59)。 +1得到当前秒数
      var time =
        year + "/" + month + "/" + data + " " + hour + ":" + min + ":" + sec;  //将转换成功的年月日小时分钟秒进行拼接
      console.log(“111”,time);
    });
  }

 效果如下:

 重点我们要掌握转换时间戳的一些方法

原文地址:https://www.cnblogs.com/p1234/p/13205020.html