时间戳转换

代码:

  timeChange(time, text) {
      //字符长度小于2时的处理
      function add0(m) {
        return String(m).padStart(2, "0"); //字符长度小于2,则在左侧用 0 填充
      }
      // 根据所传数组进行拼接时间
      function format(time, text) {
        let DealTime = new Date(time);
        let str = "";
        for (let i = 0; i < text.length; i++) {
          str += add0(timeVer(text[i].tag, DealTime)) + text[i].unit;
        }
        return str;
      }
      // 根据所传数组中的数据获取相对应的日期
      function timeVer(time, stamp) {
        let timeVer = {
          y: stamp.getFullYear(),
          m: stamp.getMonth() + 1,
          d: stamp.getDate(),
          h: stamp.getHours(),
          mm: stamp.getMinutes(),
          s: stamp.getSeconds(),
        };
        return timeVer[time];
      }
      return format(time, text);
    },

调用:

    testClick() {
      const timeCase = new Date();
      const timeCase1 = new Date().getTime();
      console.log(this.timeChange(timeCase, this.Timetxt));
      console.log(this.timeChange(timeCase1, this.Timetxt));
    },
  

    注:Timetxt: [

            { tag: "y", unit: "-" },
            { tag: "m", unit: "-" },
            { tag: "d", unit: " " },
            { tag: "h", unit: ":" },
            { tag: "mm", unit: ":" },
            { tag: "s", unit: "" },
          ], 

 

 

传参:

参数:
 time: 时间戳(例:1657525953093)或UTC时间(例:Mon Jul 11 2022 15:52:33 GMT+0800 (中国标准时间))
 text: [
         { tag: "y", unit: "-" },
         { tag: "m", unit: "-" },
         { tag: "d", unit: " " },
         { tag: "h", unit: ":" },
         { tag: "mm", unit: ":" },
         { tag: "s", unit: "" },
       ];

ps:参数 text 中 tag 属性数据为固定,可在 timeVer 方法中替换你想要使用的键名。

ps1:unit 属性为数据单位,当前获取的数据为 2022-07-11 15:56:34;如果替换为 “年” “月” “日 ”“时”“分”“秒”,则获取的数据为 2022年07月11日 16时00分46秒。

ps2:获取的数据范围可根据需求自定义调整 Timetxt 中的数据即可。

posted @ 2022-07-11 16:01  草莓糖&薄荷茶  阅读(333)  评论(0编辑  收藏  举报