时间格式化-正则表达式

hdc-web / 2024-11-10 / 原文

  // 封装工具函数:格式化时间
      function formatTime(timestamp,fmtString){
        //1.将时间戳转成date
        const date = new Date(timestamp)
        // // 获取具体时间
        // //获取年
        // const year = date.getFullYear()
        // //获取月份 
        // const month = date.getMonth()+1
        // // 获取日期
        // const day = date.getDate()
        // //获取小时
        // const hour = date.getHours()
        // //获取分钟
        // const minutes = date.getMinutes()
        // //获取秒钟
        // const second =  date.getSeconds()
        //2.创建正则
        const yearRe = /y+/i
        const monthRe = /M+/i
        // 正则和值匹配起来使用
        const dateO = {
          "y+":date.getFullYear(),
          "M+":date.getMonth()+1,
          "d+": date.getDate(),
          "h+":date.getHours(),
          "m+":date.getMinutes(),
          "s+":date.getSeconds()
        }
        // for 循环
        for (const key in dateO) {
          if(new RegExp(key).test(fmtString)){
            const value = (dateO[key]+"").padStart(2,"0")
            fmtString = fmtString.replace(new RegExp(key),value)
          }
        }
        return fmtString
      }
      const timeEl = document.querySelector(".time")
      console.log(new Date().getTime())//1729582497795
      const productJSON = {
        name:"iPhone",
        newPrice:4999,
        oldPrice:5999,
        endTime:1729582491795
      }

      timeEl.textContent =formatTime(productJSON.endTime,"yyyy-MM-dd hh:mm:ss")