feat: 使用 dayjs 替换时间处理逻辑,优化日期时间转换功能,删除不再使用的时间工具函数

This commit is contained in:
雨霖铃
2026-02-02 20:58:56 +08:00
parent 0b70c0c0c1
commit a6d85962b7
7 changed files with 100 additions and 157 deletions
@@ -1,5 +1,5 @@
import { formatWithDate, formatWithZone } from '../../../utils/timeUtils';
import { useState, useCallback } from 'react';
import dayjs from '@/utils/dayjs';
/**
* 日期时间转时间戳组件
@@ -49,7 +49,7 @@ const TIMESTAMP_UNITS = [
];
export function DatetimeToTimestamp() {
const [dateValue, setDateValue] = useState(() => formatWithZone(Date.now(), 'Asia/Shanghai'));
const [dateValue, setDateValue] = useState(() => dayjs().format('YYYY/MM/DD HH:mm:ss'));
const [selectedZone, setSelectedZone] = useState('Asia/Shanghai');
@@ -59,64 +59,54 @@ export function DatetimeToTimestamp() {
const [error, setError] = useState('');
/**
* 转换日期时间为时间戳
*/
const handleConvertDatetimeToTimestamp = useCallback(() => {
try {
setError('');
const timestamp = formatWithDate(dateValue, selectedZone);
const performConversion = useCallback(
(currentDate: string, zone: string, currentUnit: string) => {
try {
if (!currentDate) {
setError('请输入有效的日期时间');
return '';
}
if (typeof timestamp !== 'number' || isNaN(timestamp)) {
setError('无效的日期时间格式');
setResult('');
return;
const timestamp = dayjs.tz(currentDate, zone);
if (!timestamp.isValid()) {
setError('无效的日期时间格式');
return '';
}
setError('');
const ms = timestamp.valueOf();
return currentUnit === TIMESTAMP_UNITS[0].value
? ms.toString()
: Math.floor(ms / 1000).toString();
} catch (err) {
console.error('转换错误:', err);
return '';
}
},
[],
);
const finalResult = unit === 'milliseconds' ? timestamp : Math.floor(timestamp / 1000);
setResult(finalResult.toString());
} catch (err) {
console.error('转换错误:', err);
setError('转换失败,请检查输入格式');
setResult('');
}
}, [dateValue, selectedZone, unit]);
/**
* 处理日期时间输入变化
*/
const handleDateChange = useCallback((e) => {
setDateValue(e.target.value);
setError(''); // 清除错误信息
}, []);
/**
* 处理时区选择变化
*/
const handleZoneChange = useCallback((e) => {
setSelectedZone(e.target.value);
}, []);
const handleConvert = useCallback(() => {
const newResult = performConversion(dateValue, selectedZone, unit);
setResult(newResult);
}, [dateValue, selectedZone, unit, performConversion]);
/**
* 处理时间戳单位变化
*/
const handleUnitChange = useCallback(
(e) => {
(e: React.ChangeEvent<HTMLSelectElement>) => {
const newUnit = e.target.value;
setUnit(newUnit);
// 如果已有结果,重新计算
if (result) {
const currentResult = parseInt(result, 10);
if (!isNaN(currentResult)) {
const newResult =
newUnit === 'milliseconds' ? currentResult * 1000 : Math.floor(currentResult / 1000);
setResult(newResult.toString());
}
setResult(performConversion(dateValue, selectedZone, newUnit) || '');
}
},
[result],
[dateValue, selectedZone, result, performConversion],
);
return (
@@ -130,14 +120,17 @@ export function DatetimeToTimestamp() {
placeholder="输入日期时间 (如: 2024-01-01 12:00:00)"
value={dateValue}
className="datetime-input"
onChange={handleDateChange}
onChange={(e) => {
setDateValue(e.target.value);
if (error) setError('');
}}
aria-label="输入要转换的日期时间"
title="支持格式: YYYY-MM-DD HH:mm:ss"
/>
<select
value={selectedZone}
className="timezone-select"
onChange={handleZoneChange}
onChange={(e) => setSelectedZone(e.target.value)}
aria-label="选择时区"
>
{TIME_ZONE_LIST.map((zone) => (
@@ -157,7 +150,7 @@ export function DatetimeToTimestamp() {
<div className="action-group">
<button
className="converter-btn action-btn"
onClick={handleConvertDatetimeToTimestamp}
onClick={handleConvert}
aria-label="转换日期时间为时间戳"
>
@@ -1,5 +1,4 @@
import { useState, useCallback } from 'react';
import { formatWithZone } from '../../../utils/timeUtils';
/**
* 时间戳转日期时间组件
@@ -9,11 +8,6 @@ import { formatWithZone } from '../../../utils/timeUtils';
* 2. 支持多种时区选择
* 3. 支持毫秒和秒单位切换
* 4. 提供输入验证和错误提示
*
* @component
* @example
* ```jsx
* <TimestampToDatetime />
* ```
*
* @returns {JSX.Element} 时间戳转日期时间组件
@@ -48,54 +42,52 @@ const TIMESTAMP_UNITS = [
];
export function TimestampToDatetime() {
/** @type {[string, function]} 输入的时间戳值 */
const [timestampValue, setTimestampValue] = useState(() => Date.now());
/** @type {[string, function]} 转换结果 */
const [timestampValue, setTimestampValue] = useState(() => dayjs().valueOf().toString());
const [timestampResult, setTimestampResult] = useState('');
/** @type {[string, function]} 时间戳单位 ('milliseconds' | 'seconds') */
const [unit, setUnit] = useState('milliseconds');
/** @type {[string, function]} 选择的时区 */
const [selectedZone, setSelectedZone] = useState('Asia/Shanghai');
/** @type {[string, function]} 错误信息 */
const [error, setError] = useState('');
/**
* 转换时间戳为日期时间
* @type {function(): void}
*/
const handleConvertTimestampToDate = useCallback(() => {
try {
setError('');
if (!timestampValue) {
setError('请输入时间戳');
setTimestampResult('');
return;
const performConversion = useCallback(
(timestampValue: string, selectedZone: string, unit: string) => {
if (!timestampValue || timestampValue.trim() === '') {
setError('请输入有效的日期时间');
return '';
}
const numericValue = Number(timestampValue);
if (isNaN(numericValue)) {
setError('无效的时间戳格式');
setTimestampResult('');
return;
}
try {
const numberValue = Number(timestampValue);
if (isNaN(numberValue)) {
setError('时间戳必须是数字');
return '';
}
const result = formatWithZone(numericValue, selectedZone, unit);
setTimestampResult(result);
} catch (err) {
console.error('转换时间戳出错:', err);
setError('转换失败,请检查输入格式');
setTimestampResult('');
}
}, [timestampValue, selectedZone, unit]);
const d = unit === TIMESTAMP_UNITS[0].value ? dayjs(numberValue) : dayjs.unix(numberValue);
if (!d.isValid()) {
setError('无效的时间戳格式');
return '';
}
const dateTime = d.tz(selectedZone).format('YYYY/MM/DD HH:mm:ss');
setError('');
return dateTime;
} catch (err) {
console.error('转换错误:', err);
return '';
}
},
[],
);
const handleConvert = useCallback(() => {
const newResult = performConversion(timestampValue, selectedZone, unit);
setTimestampResult(newResult);
}, [timestampValue, selectedZone, unit, performConversion]);
/**
* 处理时间戳输入变化
* @type {function(React.ChangeEvent<HTMLInputElement>): void}
*/
const handleInputChange = useCallback((e) => {
setTimestampValue(e.target.value);
@@ -104,18 +96,18 @@ export function TimestampToDatetime() {
/**
* 处理时区选择变化
* @type {function(React.ChangeEvent<HTMLSelectElement>): void}
*/
const handleZoneChange = useCallback((e) => {
setSelectedZone(e.target.value);
const handleZoneChange = useCallback((e: React.ChangeEvent<HTMLSelectElement>) => {
const newZone = e.target.value;
setSelectedZone(newZone);
}, []);
/**
* 处理时间戳单位变化
* @type {function(React.ChangeEvent<HTMLSelectElement>): void}
*/
const handleUnitChange = useCallback((e) => {
setUnit(e.target.value);
const handleUnitChange = useCallback((e: React.ChangeEvent<HTMLSelectElement>) => {
const newUnit = e.target.value;
setUnit(newUnit);
}, []);
return (
@@ -156,7 +148,7 @@ export function TimestampToDatetime() {
<div className="action-group">
<button
className="converter-btn action-btn"
onClick={handleConvertTimestampToDate}
onClick={handleConvert}
aria-label="转换时间戳为日期时间"
>
+7
View File
@@ -17,6 +17,7 @@
"@testing-library/react": "^16.3.1",
"@testing-library/user-event": "^13.5.0",
"date-fns": "^4.1.0",
"dayjs": "^1.11.19",
"dexie": "^4.2.1",
"dexie-react-hooks": "^4.2.0",
"react": "^19.2.3",
@@ -3744,6 +3745,12 @@
"url": "https://github.com/sponsors/kossnocorp"
}
},
"node_modules/dayjs": {
"version": "1.11.19",
"resolved": "https://registry.npmmirror.com/dayjs/-/dayjs-1.11.19.tgz",
"integrity": "sha512-t5EcLVS6QPBNqM2z8fakk/NKel+Xzshgt8FFKAn+qwlD1pzZWxh0nVCrvFK7ZDb6XucZeF9z8C7CBWTRIVApAw==",
"license": "MIT"
},
"node_modules/debounce": {
"version": "1.2.1",
"resolved": "https://registry.npmmirror.com/debounce/-/debounce-1.2.1.tgz",
+1
View File
@@ -25,6 +25,7 @@
"@testing-library/react": "^16.3.1",
"@testing-library/user-event": "^13.5.0",
"date-fns": "^4.1.0",
"dayjs": "^1.11.19",
"dexie": "^4.2.1",
"dexie-react-hooks": "^4.2.0",
"react": "^19.2.3",
+1 -1
View File
@@ -35,7 +35,7 @@
// 如果你的 @/utils/... 爆红,可以手动添加这个映射。
// WXT 通常会自动处理,但在这里显式声明有助于 VS Code 智能提示。
"paths": {
"@/*": ["./entrypoints/*", "./components/*", "./utils/*", "./assets/*"]
"@/*": ["./*"]
},
"types": ["chrome", "webextension-polyfill"],
"noImplicitAny": false
+8
View File
@@ -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;
-58
View File
@@ -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;
}
};