fix(timestamp): 优化日期转时间戳函数支持时区处理

移除调试日志,增强 `convertDateToTimestamp` 函数的健壮性:
- 支持输入 Date 对象和字符串
- 增加对时区的支持,通过计算目标时区偏移量得到正确时间戳
- 添加错误捕获与返回明确的错误信息
- 提取获取时区偏移量逻辑为独立函数 `getTimeZoneOffset`
This commit is contained in:
雨霖铃
2025-11-18 23:38:50 +08:00
parent bc1943dc16
commit 951a0579ce
2 changed files with 42 additions and 9 deletions
-2
View File
@@ -163,8 +163,6 @@ export function handleConvertDateToTimestamp() {
// 转换为时间戳 // 转换为时间戳
const timestamp = convertDateToTimestamp(date, selectedTimezone); const timestamp = convertDateToTimestamp(date, selectedTimezone);
console.log('转换后的时间戳:', timestamp);
if (isNaN(timestamp)) { if (isNaN(timestamp)) {
dateInputResult.value = '无效的日期字符串'; dateInputResult.value = '无效的日期字符串';
dateInputResult.style.borderColor = '#dc3545'; dateInputResult.style.borderColor = '#dc3545';
+42 -7
View File
@@ -64,7 +64,7 @@ export function convertTimestampToDate(
/** /**
* 转换日期格式为时间戳 * 转换日期格式为时间戳
* @param {string} date - 输入的日期字符串 * @param {string|Date} date - 输入的日期字符串或Date对象
* @param {string} timeZone - 时区,默认为本地时区 * @param {string} timeZone - 时区,默认为本地时区
* @returns {number|string} 时间戳或错误信息 * @returns {number|string} 时间戳或错误信息
*/ */
@@ -72,10 +72,45 @@ export function convertDateToTimestamp(
date, date,
timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone
) { ) {
return new Date( try {
Intl.DateTimeFormat('en-US', { // 创建日期对象
timeZone: timeZone, const dateObj = new Date(date);
hour12: false,
}).format(date) // 检查日期是否有效
).getTime(); if (isNaN(dateObj.getTime())) {
return '无效的日期';
}
// 如果提供了时区,则需要特殊处理
if (timeZone) {
// 获取给定时区相对于UTC的时间差(毫秒)
const utc = dateObj.getTime() + dateObj.getTimezoneOffset() * 60000;
// 计算目标时区相对于UTC的偏移量
const targetOffset = getTimeZoneOffset(timeZone);
// 返回目标时区对应的时间戳
const targetTimestamp = utc + targetOffset;
return targetTimestamp;
} else {
// 没有时区参数,直接返回时间戳
const timestamp = dateObj.getTime();
console.log('timestamp: ', timestamp);
return timestamp;
}
} catch (error) {
return '日期转换错误: ' + error.message;
}
}
/**
* 获取指定时区相对于UTC的偏移量(毫秒)
* @param {string} timeZone - 时区名称
* @returns {number} 偏移量(毫秒)
*/
function getTimeZoneOffset(timeZone) {
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();
} }