Skip to content

Commit aa53df8

Browse files
committed
refactor(timeFormat): fix date parsing logic
1 parent ff906b2 commit aa53df8

File tree

2 files changed

+17
-14
lines changed

2 files changed

+17
-14
lines changed

src/timeFormat.ts

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,42 @@
1-
import { isString } from '.'
21
import type { Numeric } from './types'
32

43
export type TimeFormatItem = 'y' | 'm' | 'd' | 'h' | 'M' | 's'
54

65
/**
76
* @description 格式化时间
8-
* @param timestamp 需要格式化的时间戳
7+
* @param dateTime 需要格式化的时间
98
* @param format 格式化规则 yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合 默认yyyy-mm-dd
109
*/
1110

12-
export function timeFormat(timestamp: Numeric, format = 'yyyy-mm-dd') {
11+
export function timeFormat(dateTime: Numeric, format = 'yyyy-mm-dd') {
1312
let date: Date
1413

1514
// 若传入时间为假值,则取当前时间
16-
if (!timestamp) {
15+
if (!dateTime) {
1716
date = new Date()
1817
}
1918

2019
// 若为unix秒时间戳,则转为毫秒时间戳
21-
else if (/^\d{10}$/.test(timestamp?.toString().trim())) {
22-
date = new Date(+timestamp * 1000)
20+
else if (/^\d{10}$/.test(dateTime?.toString().trim())) {
21+
date = new Date(+dateTime * 1000)
2322
}
2423

2524
// 若用户传入字符串格式时间戳,new Date无法解析,需做兼容
26-
else if (isString(timestamp)) {
27-
date = new Date(Number(timestamp))
25+
else if (typeof dateTime === 'string' && /^\d+$/.test(dateTime.trim())) {
26+
date = new Date(Number(dateTime))
27+
}
28+
// 处理平台性差异,在Safari/Webkit中,new Date仅支持/作为分割符的字符串时间
29+
else if (
30+
typeof dateTime === 'string' &&
31+
dateTime.includes('-') &&
32+
!dateTime.includes('T')
33+
) {
34+
date = new Date(dateTime.replace(/-/g, '/'))
2835
}
29-
3036
// 其他都认为符合 RFC 2822 规范
3137
else {
32-
// 处理平台性差异,在Safari/Webkit中,new Date仅支持/作为分割符的字符串时间
33-
date = new Date(
34-
typeof timestamp === 'string' ? timestamp.replace(/-/g, '/') : timestamp
35-
)
38+
date = new Date(dateTime)
3639
}
37-
3840
const timeSource = {
3941
y: date.getFullYear().toString(), // 年
4042
m: (date.getMonth() + 1).toString().padStart(2, '0'), // 月

tests/timeFormat.test.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ describe('timeFormat', () => {
1010
const M = date.getMinutes().toString().padStart(2, '0') // 分
1111
const s = date.getSeconds().toString().padStart(2, '0') // 秒
1212

13+
expect(timeFormat('2025-06-02')).toBe(`${y}-${m}-${d}`)
1314
expect(timeFormat(date.getTime())).toBe(`${y}-${m}-${d}`)
1415
expect(timeFormat(date.getTime(), 'yyyy/mm/dd')).toBe(`${y}/${m}/${d}`)
1516
expect(timeFormat(date.getTime(), 'yyyy-mm-dd hh:MM:ss')).toBe(

0 commit comments

Comments
 (0)