使用 str.replace(reg,function(){})格式化时间

const formatDate = (date, format) => {
      if (!date) return
      if (!format) {
        format = 'yyyy-MM-dd'
      }
      switch (typeof date) {
      case 'string':
        date = new Date(date.replace(/-/g, '/'))
        break
      case 'number':
        date = new Date(date)
        break
      }
      if (date instanceof Date) {
        const dict = {
          yyyy: date.getFullYear(),
          M: date.getMonth() + 1,
          H: date.getHours(),
          m: date.getMinutes(),
          s: date.getSeconds(),
          MM: ('' + (date.getMonth() + 101)).slice(1),
          dd: ('' + (date.getDate() + 100)).slice(1),
          HH: ('' + (date.getHours() + 100)).slice(1),
          mm: ('' + (date.getMinutes() + 100)).slice(1),
          ss: ('' + (date.getSeconds() + 100)).slice(1),
        }
        return format.replace(/(yyyy|MM?|dd?|HH?|ss?|mm?)/g, function () {
          return dict[arguments[0]]
        })
      }
    };
    
    let timeStr1 = formatDate('2023-04-23', 'yyyy年M月dd日')
    let timeStr2 = formatDate('2023-04-23 12:00', 'yyyy年M月dd日 HH:mm')
    console.log(timeStr1)
    console.log(timeStr2)

你可能感兴趣的:(javascript,vue.js,开发语言)