dateFormate.js
2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import dayjs from 'dayjs'
export function formattedTime(rawTime) {
try {
// 格式校验
if (!/^\d{12}$/.test(rawTime)) {
this.$message.error('无效的时间格式 (需要12位数字)')
}
// 拆分时间组件
const components = {
year: parseInt(rawTime.slice(0, 2)),
month: parseInt(rawTime.slice(2, 4)),
day: parseInt(rawTime.slice(4, 6)),
hour: parseInt(rawTime.slice(6, 8)),
minute: parseInt(rawTime.slice(8, 10)),
second: parseInt(rawTime.slice(10, 12))
}
// 验证有效性
if (
components.month < 1 || components.month > 12 ||
components.day < 1 || components.day > 31 ||
components.hour > 23 ||
components.minute > 59 ||
components.second > 59
) {
this.$message.error('时间参数超出有效范围')
}
// 转换为完整年份 (假设是20世纪和21世纪)
const fullYear = components.year < 50 ?
2000 + components.year :
1900 + components.year
// 使用 dayjs 构建日期对象
const date = dayjs()
.year(fullYear)
.month(components.month - 1) // 月份从0开始
.date(components.day)
.hour(components.hour)
.minute(components.minute)
.second(components.second)
// 验证日期是否有效
if (!date.isValid()) {
this.$message.error('生成的时间无效')
}
// 返回格式化结果
return date.format('YYYY-MM-DD HH:mm:ss')
} catch (err) {
console.error('时间转换错误:', err)
this.$message.error('时间转换失败')
}
}
export function convertTimeFormat(rawTime, inputFormat, outputFormat) {
try {
// 特殊处理时间戳
if (inputFormat === 'X' || inputFormat === 'x') {
const timestamp = inputFormat === 'X' ?
parseInt(rawTime) * 1000 : parseInt(rawTime);
return dayjs(timestamp).format(outputFormat);
}
// 使用 Day.js 解析输入时间
const dateObj = dayjs(rawTime, inputFormat);
// 验证解析结果
if (!dateObj.isValid()) {
console.log('输入时间无效')
return '转换失败: 无法解析输入时间'
}
// 转换为目标格式
return dateObj.format(outputFormat);
} catch (error) {
console.error('时间转换错误:', error);
return `转换失败: ${error.message}`;
}
}