Skip to content

Commit 25668ac

Browse files
author
puhui999
committed
add: 迁移v2版本的日期格式化函数到vue3中
1 parent bf2b4ce commit 25668ac

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

src/utils/formatTime.ts

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,51 @@ export function formatDate(date: Date, format: string): string {
6464
}
6565
return format
6666
}
67+
// 日期格式化
68+
export function parseTime(time: any, pattern?: string) {
69+
if (arguments.length === 0 || !time) {
70+
return null
71+
}
72+
const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
73+
let date
74+
if (typeof time === 'object') {
75+
date = time
76+
} else {
77+
if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
78+
time = parseInt(time)
79+
} else if (typeof time === 'string') {
80+
time = time
81+
.replace(new RegExp(/-/gm), '/')
82+
.replace('T', ' ')
83+
.replace(new RegExp(/\.\d{3}/gm), '')
84+
}
85+
if (typeof time === 'number' && time.toString().length === 10) {
86+
time = time * 1000
87+
}
88+
date = new Date(time)
89+
}
90+
const formatObj = {
91+
y: date.getFullYear(),
92+
m: date.getMonth() + 1,
93+
d: date.getDate(),
94+
h: date.getHours(),
95+
i: date.getMinutes(),
96+
s: date.getSeconds(),
97+
a: date.getDay()
98+
}
99+
const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
100+
let value = formatObj[key]
101+
// Note: getDay() returns 0 on Sunday
102+
if (key === 'a') {
103+
return ['日', '一', '二', '三', '四', '五', '六'][value]
104+
}
105+
if (result.length > 0 && value < 10) {
106+
value = '0' + value
107+
}
108+
return value || 0
109+
})
110+
return time_str
111+
}
67112

68113
/**
69114
* 获取当前日期是第几周

0 commit comments

Comments
 (0)