forked from gzt/A8000
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.5 KiB
56 lines
1.5 KiB
// dateUtils.ts
|
|
|
|
/**
|
|
* 日期格式化函数
|
|
* @param timestamp - 时间戳(支持秒或毫秒),字符串,或Date对象
|
|
* @param format - 格式化字符串,例如:'YYYY-MM-DD HH:mm:ss'
|
|
* @returns 格式化后的日期字符串
|
|
*/
|
|
export function formatDate(
|
|
timestamp: number | string | Date,
|
|
format: string = 'YYYY-MM-DD HH:mm:ss'
|
|
): string {
|
|
if (!timestamp) return '';
|
|
|
|
let date: Date;
|
|
|
|
// 处理不同类型的输入
|
|
if (timestamp instanceof Date) {
|
|
date = timestamp;
|
|
} else {
|
|
let tsNumber = Number(timestamp);
|
|
if (isNaN(tsNumber)) {
|
|
console.error('Invalid timestamp:', timestamp);
|
|
return '';
|
|
}
|
|
|
|
// 判断时间戳是秒还是毫秒级别
|
|
if (String(Math.floor(tsNumber)).length === 10) {
|
|
tsNumber *= 1000; // 秒级时间戳转毫秒
|
|
}
|
|
|
|
date = new Date(tsNumber);
|
|
}
|
|
|
|
if (isNaN(date.getTime())) {
|
|
console.error('Invalid date:', date);
|
|
return '';
|
|
}
|
|
|
|
const map: { [key in 'YYYY' | 'MM' | 'DD' | 'HH' | 'mm' | 'ss']: string } = {
|
|
YYYY: date.getFullYear().toString(),
|
|
MM: ('0' + (date.getMonth() + 1)).slice(-2),
|
|
DD: ('0' + date.getDate()).slice(-2),
|
|
HH: ('0' + date.getHours()).slice(-2),
|
|
mm: ('0' + date.getMinutes()).slice(-2),
|
|
ss: ('0' + date.getSeconds()).slice(-2),
|
|
};
|
|
|
|
// 使用正则替换格式字符串中的标记
|
|
const formattedDate = format.replace(/YYYY|MM|DD|HH|mm|ss/g, (pattern) => {
|
|
return map[pattern as keyof typeof map];
|
|
});
|
|
|
|
return formattedDate;
|
|
}
|
|
|