feat: 使用 dayjs 替换时间处理逻辑,优化日期时间转换功能,删除不再使用的时间工具函数
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
import dayjs from 'dayjs';
|
||||
import utc from 'dayjs/plugin/utc';
|
||||
import timezone from 'dayjs/plugin/timezone';
|
||||
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezone);
|
||||
|
||||
export default dayjs;
|
||||
@@ -1,58 +0,0 @@
|
||||
export const formatWithZone = (
|
||||
timestamp: number | string,
|
||||
zone = 'Asia/Shanghai',
|
||||
unit = 'milliseconds',
|
||||
) => {
|
||||
try {
|
||||
const ms = unit === 'milliseconds' ? Number(timestamp) : Number(timestamp) * 1000;
|
||||
return new Intl.DateTimeFormat('zh-CN', {
|
||||
year: 'numeric',
|
||||
month: 'numeric',
|
||||
day: 'numeric',
|
||||
hour: 'numeric',
|
||||
minute: 'numeric',
|
||||
second: 'numeric',
|
||||
timeZone: zone,
|
||||
}).format(ms);
|
||||
} catch (e) {
|
||||
console.error('formatWithZone error:', e);
|
||||
return '格式错误';
|
||||
}
|
||||
};
|
||||
|
||||
export const getTimeZoneOffset = (timeZone: string) => {
|
||||
const now = new Date();
|
||||
const utc = new Date(now.toLocaleString('en-US', { timeZone: 'UTC' }));
|
||||
const target = new Date(now.toLocaleString('en-US', { timeZone: timeZone }));
|
||||
return target.getTime() - utc.getTime();
|
||||
};
|
||||
|
||||
export const formatWithDate = (
|
||||
date: string,
|
||||
timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
) => {
|
||||
try {
|
||||
// 创建日期对象
|
||||
const dateObj = new Date(date);
|
||||
|
||||
// 检查日期是否有效
|
||||
if (isNaN(dateObj.getTime())) {
|
||||
return '无效的日期';
|
||||
}
|
||||
|
||||
// 如果提供了时区,则需要特殊处理
|
||||
if (timeZone) {
|
||||
// 获取给定时区相对于UTC的时间差(毫秒)
|
||||
const utc = dateObj.getTime() + dateObj.getTimezoneOffset() * 60000;
|
||||
|
||||
// 计算目标时区相对于UTC的偏移量
|
||||
const targetOffset = getTimeZoneOffset(timeZone);
|
||||
|
||||
return utc + targetOffset;
|
||||
} else {
|
||||
return dateObj.getTime();
|
||||
}
|
||||
} catch (error) {
|
||||
return '日期转换错误: ' + error;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user