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

自定义获取格式化日期时间格式 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

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值