Refactor time utility functions for improved type safety and error handling

- Removed deprecated formatDate function.
- Enhanced formatWithZone to support TypeScript types for parameters.
- Updated getTimeZoneOffset to use TypeScript types.
- Improved formatWithDate for better error messages and type safety.
This commit is contained in:
雨霖铃
2026-01-28 22:39:44 +08:00
parent 710bffd2f8
commit 92026ee7fa
6 changed files with 813 additions and 843 deletions
+18 -30
View File
@@ -1,20 +1,8 @@
export function formatDate(value, timezone = 'Asia/Shanghai') {
return (new Intl.DateTimeFormat('zh-CN', {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZone: timezone,
})).format(value);
}
export const TimezoneOptions = ({zones}) => {
return (zones.map((zone) => (<option key={zone} value={zone}>{zone}</option>)));
}
export const formatWithZone = (timestamp, zone = 'Asia/Shanghai', unit = 'milliseconds') => {
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', {
@@ -29,41 +17,41 @@ export const formatWithZone = (timestamp, zone = 'Asia/Shanghai', unit = 'millis
} catch (e) {
return '格式错误';
}
}
};
export const getTimeZoneOffset = (timeZone) => {
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}));
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,
timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone
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.message;
return '日期转换错误: ' + error;
}
}
};