获取指定格式日期

... 2025-7-10 Code 小于 1 分钟

function formatDate(time, format = 'YY-MM-DD hh:mm:ss') {
  let date = time ? new Date(time) : new Date()
  let arr = Array.apply(null, { length: 10 }).map((item, index) => '0' + index)
  let TimeObj = {
    YY: date.getFullYear(),
    MM: arr[date.getMonth() + 1] || date.getMonth() + 1,
    DD: arr[date.getDate()] || date.getDate(),
    hh: arr[date.getHours()] || date.getHours(),
    mm: arr[date.getMinutes()] || date.getMinutes(),
    ss: arr[date.getSeconds()] || date.getSeconds(),
  }
  return format.replace(/YY|MM|DD|hh|mm|ss/g, (matched) => TimeObj[matched])
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 使用

formatDate() // 2022-05-26 15:30:58
formatDate(null, 'YY-MM-DD') // 2022-05-26
formatDate(null, 'hh:mm:ss') // 15:30:58

formatDate(null, 'YYMMDD') // 20220526
formatDate(null, 'YY/MM/DD') // 2022/05/26
formatDate(null, 'YY年MM月DD日') // 2022年05月26日

formatDate('Thu May 26 2022 10:08:44') // 2022-05-26 10:08:44
formatDate('2022 5 26') // '2022-05-26 00:00:00'
1
2
3
4
5
6
7
8
9
10
上次编辑于: 2025年7月10日 04:01
贡献者: HugStars