时间戳转换(第二版)

代码:

 timestampTostr(timestamp, format ="yyyy-mm-dd hh:mm:ss") {
     var date = new Date(timestamp); // 时间戳为10位需*1000,时间戳为13位的话不需乘1000
      //转换的时间格式
      var Y = date.getFullYear();
      var M = add0(date.getMonth() + 1);
      var D = add0(date.getDate());
      var h = add0(date.getHours());
      var m = add0(date.getMinutes());
      var s = add0(date.getSeconds());

      const dateJson = {
        "yyyy-mm-dd hh:mm:ss":
          Y + "-" + M + "-" + D + " " + h + ":" + m + ":" + s,
      };
      function add0(m) {
        return String(m).padStart(2, "0"); //字符长度小于2,则在左侧用 0 填充
      }
      return dateJson[format];
},

示例:

    this.timestampTostr(new Date());                // 2022-08-15 16:25:56
      this.timestampTostr(new Date(), "yyyy-mm-dd");  // 2022-08-15
      this.timestampTostr(new Date(), "yyyymmdd");    // 20220815

 

posted @ 2022-08-15 16:27  草莓糖&薄荷茶  阅读(58)  评论(0编辑  收藏  举报