function formatDate(date, format) {
  const map = {
    'M': date.getMonth() + 1, // 月份
    'd': date.getDate(), // 日
    'h': date.getHours(), // 小时
    'm': date.getMinutes(), // 分
    's': date.getSeconds(), // 秒
    'q': Math.floor((date.getMonth() + 3) / 3), // 季度
    'S': date.getMilliseconds() // 毫秒
  }
  format = format.replace(/([yMdhmsqS])+/g, (all, t) => {
    let v = map[t]
    if (v !== undefined) {
      if (all.length > 1) {
        v = '0' + v
        v = v.substr(v.length - 2)
      }
      return v
    } else if (t === 'y') {
      return (date.getFullYear() + '').substr(4 - all.length)
    }
    return all
  })
  return format
}

const date = new Date()
console.log(formatDate(date, 'yyyy-MM-dd hh:mm:ss.S')) // 2022-01-01 12:00:00.000
console.log(formatDate(date, 'yyyy-M-d h:m:s.S')) // 2022-1-1 12:0:0.000

这里是一个简单的时间格式化函数,可以通过传入不同的格式化字符串,输出不同格式的时间。函数的核心是通过正则表达式匹配格式化字符串中的各种时间单位,然后使用一个对象映射表,确定对应的时间值,再根据格式化字符串中的格式要求,进行输出。

JavaScript实现时间格式化输出

原文地址: https://www.cveoy.top/t/topic/NfQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录