时间戳转换

代码:

复制代码
  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 @   草莓糖&薄荷茶  阅读(349)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示