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