自定义获取格式化日期时间格式 TypeScript

GetDate(‘YYYY 年 M 月 D 日’)
GetDate(‘YYYY-MM-DD’)
GetDate(‘HH:mm:ss’)

/**
 * 获取时间并格式化函数
 * @param M 格式模板 如: YYYY-MM-DD ...
 * @param Time 可选传入时间参数 默认为 Now
 */
const GetDate = (M: string, Time: Date | null | string | number = null) => {
  let D: Date = Time ? new Date(Time) : new Date()
  let P: RegExp = /(Y{2,4}|M{1,2}|D{1,2}|H{1,2}|h{1,2}|m{1,2}|s{1,2}|C{1,2}|W{1,2})/g
  let ToZ: any = (S: string | number) => ((Number(S) < 10) ? '0' + S : S)
  let DS: string = M.replace(P, ($0: string) => {
    switch ($0) {
      case 'YY': return D.getFullYear().toString().slice(-2)
      case 'YYYY': return D.getFullYear()
      case 'M': return D.getMonth() + 1
      case 'MM': return ToZ(D.getMonth() + 1)
      case 'D': return D.getDate()
      case 'DD': return ToZ(D.getDate())
      case 'W': return D.getDay()
      case 'WW': return ['日', '一', '二', '三', '四', '五', '六'][D.getDay()]
      case 'H': return D.getHours()
      case 'HH': return ToZ(D.getHours())
      case 'm': return D.getMinutes()
      case 'mm': return ToZ(D.getMinutes())
      case 's': return D.getSeconds()
      case 'ss': return ToZ(D.getSeconds())
      case 'C': return Math.trunc(D.getTime() / 1000)
      case 'CC': return D.getTime()
      default: return $0
    }
  })
  return DS
}

console.log(GetDate('年: YY YYYY \n月: M MM \n日: D DD \n星期: W WW\n时: H HH\n分: m mm\n秒: s ss\n时间戳: C 毫秒=> CC','2023/1/1 00:00:00'));

打印内容

年: 23 2023
月: 1 01
日: 1 01
星期: 0 日
时: 0 00
分: 0 00
秒: 0 00
时间戳: 1672502400 毫秒=> 1672502400000