refactor:优化时间戳工具,优化CopyButton
This commit is contained in:
@@ -1,90 +1,133 @@
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { useState, useCallback, FC, ReactNode, useEffect } from 'react';
|
||||
import Button, { ButtonProps } from '@mui/material/Button';
|
||||
import Snackbar from '@mui/material/Snackbar';
|
||||
import Alert, { AlertColor } from '@mui/material/Alert';
|
||||
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
|
||||
import CheckIcon from '@mui/icons-material/Check';
|
||||
|
||||
const CopyButton = ({
|
||||
text = '要复制的文本',
|
||||
buttonText = '复制文本',
|
||||
className = 'action-btn',
|
||||
type CopyStatus = 'idle' | 'copying' | 'success' | 'error';
|
||||
|
||||
interface CopyButtonProps extends Omit<ButtonProps, 'onClick' | 'variant'> {
|
||||
textToCopy: string | number;
|
||||
buttonText?: ReactNode;
|
||||
successMessage?: string;
|
||||
errorMessage?: string;
|
||||
variant?: ButtonProps['variant'];
|
||||
}
|
||||
|
||||
const CopyButton: FC<CopyButtonProps> = ({
|
||||
textToCopy,
|
||||
buttonText = '复制',
|
||||
successMessage = '复制成功!',
|
||||
errorMessage = '复制失败,请手动复制。',
|
||||
copyingMessage = '复制中...',
|
||||
variant = 'contained',
|
||||
...buttonProps
|
||||
}) => {
|
||||
const [status, setStatus] = useState('idle'); // 'idle' | 'copying' | 'success' | 'error'
|
||||
const [status, setStatus] = useState<CopyStatus>('idle');
|
||||
const [openSnackbar, setOpenSnackbar] = useState(false);
|
||||
const [snackbarContent, setSnackbarContent] = useState<{
|
||||
message: string;
|
||||
severity: AlertColor;
|
||||
} | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let timer: number;
|
||||
if (status === 'success' || status === 'error') {
|
||||
timer = window.setTimeout(() => {
|
||||
setStatus('idle');
|
||||
}, 2000);
|
||||
const timer = setTimeout(() => setStatus('idle'), 2000);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
return undefined;
|
||||
}, [status]);
|
||||
|
||||
const performCopy = useCallback(async () => {
|
||||
if (!text) {
|
||||
if (!textToCopy) {
|
||||
console.warn('没有提供要复制的文本');
|
||||
return false;
|
||||
}
|
||||
|
||||
const safeText = String(text);
|
||||
|
||||
if (navigator.clipboard && navigator.clipboard.writeText) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(safeText);
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error('使用 Clipboard API 复制失败:', err);
|
||||
return false;
|
||||
}
|
||||
const safeText = String(textToCopy);
|
||||
try {
|
||||
await navigator.clipboard.writeText(safeText);
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error('使用 Clipboard API 复制失败:', err);
|
||||
return false;
|
||||
}
|
||||
|
||||
return false;
|
||||
}, [text]);
|
||||
}, [textToCopy]);
|
||||
|
||||
const handleClick = useCallback(async () => {
|
||||
setStatus('copying');
|
||||
if (status !== 'idle') return;
|
||||
|
||||
setStatus('copying');
|
||||
let isSuccess = false;
|
||||
try {
|
||||
const isSuccess = await performCopy();
|
||||
setStatus(isSuccess ? 'success' : 'error');
|
||||
[isSuccess] = await Promise.all([
|
||||
performCopy(),
|
||||
new Promise((resolve) => setTimeout(resolve, 300)),
|
||||
]);
|
||||
} catch (error) {
|
||||
console.error('复制时出错:', error);
|
||||
setStatus('error');
|
||||
isSuccess = false;
|
||||
} finally {
|
||||
const newStatus = isSuccess ? 'success' : 'error';
|
||||
setStatus(newStatus);
|
||||
setSnackbarContent({
|
||||
message: isSuccess ? successMessage : errorMessage,
|
||||
severity: newStatus,
|
||||
});
|
||||
setOpenSnackbar(true);
|
||||
}
|
||||
}, [performCopy]);
|
||||
}, [performCopy, status, successMessage, errorMessage]);
|
||||
|
||||
// 根据状态计算当前显示的文本
|
||||
const currentText =
|
||||
status === 'success'
|
||||
? successMessage
|
||||
: status === 'error'
|
||||
? errorMessage
|
||||
: status === 'copying'
|
||||
? copyingMessage
|
||||
: buttonText;
|
||||
const handleCloseSnackbar = (_event?: Event | React.SyntheticEvent, reason?: string) => {
|
||||
if (reason === 'clickaway') return;
|
||||
setOpenSnackbar(false);
|
||||
};
|
||||
|
||||
// 动态样式:只在非默认状态下覆盖颜色,平时让 className 控制
|
||||
const getStyle = () => {
|
||||
const renderButtonIcon = () => {
|
||||
if (status === 'success') {
|
||||
return { backgroundColor: '#4CAF50', color: 'white' };
|
||||
return <CheckIcon sx={{ mr: 1 }} fontSize="small" />;
|
||||
}
|
||||
if (status === 'error') {
|
||||
return { backgroundColor: '#f44336', color: 'white' };
|
||||
}
|
||||
|
||||
return {};
|
||||
return <ContentCopyIcon sx={{ mr: 1 }} fontSize="small" />;
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={handleClick}
|
||||
className={`${className} ${status} copy-button`}
|
||||
style={getStyle()}
|
||||
disabled={status === 'success' || status === 'copying'}
|
||||
>
|
||||
{currentText}
|
||||
</button>
|
||||
<>
|
||||
<Button
|
||||
onClick={handleClick}
|
||||
disabled={status !== 'idle'}
|
||||
variant={variant}
|
||||
{...buttonProps}
|
||||
sx={{
|
||||
...buttonProps.sx,
|
||||
transition: 'background-color 0.3s',
|
||||
...(status === 'success' && {
|
||||
bgcolor: 'success.main',
|
||||
'&:hover': {
|
||||
bgcolor: 'success.dark',
|
||||
},
|
||||
}),
|
||||
}}
|
||||
>
|
||||
{renderButtonIcon()}
|
||||
{buttonText}
|
||||
</Button>
|
||||
<Snackbar
|
||||
open={openSnackbar}
|
||||
autoHideDuration={2000}
|
||||
onClose={handleCloseSnackbar}
|
||||
anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
|
||||
>
|
||||
{snackbarContent ? (
|
||||
<Alert
|
||||
onClose={handleCloseSnackbar}
|
||||
severity={snackbarContent.severity}
|
||||
variant="filled"
|
||||
sx={{ width: '100%' }}
|
||||
>
|
||||
{snackbarContent.message}
|
||||
</Alert>
|
||||
) : undefined}
|
||||
</Snackbar>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,26 +1,19 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import dayjs from '@/utils/dayjs';
|
||||
import {
|
||||
Button,
|
||||
TextField,
|
||||
Select,
|
||||
MenuItem,
|
||||
FormControl,
|
||||
InputLabel,
|
||||
Paper,
|
||||
Typography,
|
||||
Stack,
|
||||
Box,
|
||||
SelectChangeEvent,
|
||||
} from '@mui/material';
|
||||
|
||||
/**
|
||||
* 日期时间转时间戳组件
|
||||
*
|
||||
* 功能特性:
|
||||
* 1. 将日期时间字符串转换为时间戳
|
||||
* 2. 支持多种时区选择
|
||||
* 3. 支持毫秒和秒单位切换
|
||||
* 4. 提供输入验证和错误提示
|
||||
* 5. 实时单位转换
|
||||
*
|
||||
* @component
|
||||
* @example
|
||||
* ```jsx
|
||||
* <DatetimeToTimestamp />
|
||||
* ```
|
||||
*
|
||||
* @returns {JSX.Element} 日期时间转时间戳组件
|
||||
*/
|
||||
|
||||
// 常用时区列表
|
||||
const TIME_ZONE_LIST = [
|
||||
'America/New_York',
|
||||
'America/Chicago',
|
||||
@@ -42,48 +35,32 @@ const TIME_ZONE_LIST = [
|
||||
'Pacific/Auckland',
|
||||
];
|
||||
|
||||
// 时间戳单位选项
|
||||
const TIMESTAMP_UNITS = [
|
||||
{ value: 'milliseconds', label: '毫秒(ms)' },
|
||||
{ value: 'seconds', label: '秒(s)' },
|
||||
{ value: 'milliseconds', label: '毫秒 (ms)' },
|
||||
{ value: 'seconds', label: '秒 (s)' },
|
||||
];
|
||||
|
||||
export function DatetimeToTimestamp() {
|
||||
const [dateValue, setDateValue] = useState(() => dayjs().format('YYYY/MM/DD HH:mm:ss'));
|
||||
|
||||
const [selectedZone, setSelectedZone] = useState('Asia/Shanghai');
|
||||
|
||||
const [result, setResult] = useState('');
|
||||
|
||||
const [unit, setUnit] = useState('milliseconds');
|
||||
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const performConversion = useCallback(
|
||||
(currentDate: string, zone: string, currentUnit: string) => {
|
||||
try {
|
||||
if (!currentDate) {
|
||||
setError('请输入有效的日期时间');
|
||||
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);
|
||||
if (!currentDate) {
|
||||
setError('请输入有效的日期时间');
|
||||
return '';
|
||||
}
|
||||
const timestamp = dayjs.tz(currentDate, zone);
|
||||
if (!timestamp.isValid()) {
|
||||
setError('无效的日期时间格式');
|
||||
return '';
|
||||
}
|
||||
setError('');
|
||||
const ms = timestamp.valueOf();
|
||||
return currentUnit === 'milliseconds' ? ms.toString() : Math.floor(ms / 1000).toString();
|
||||
},
|
||||
[],
|
||||
);
|
||||
@@ -93,15 +70,10 @@ export function DatetimeToTimestamp() {
|
||||
setResult(newResult);
|
||||
}, [dateValue, selectedZone, unit, performConversion]);
|
||||
|
||||
/**
|
||||
* 处理时间戳单位变化
|
||||
*/
|
||||
const handleUnitChange = useCallback(
|
||||
(e: React.ChangeEvent<HTMLSelectElement>) => {
|
||||
(e: SelectChangeEvent<string>) => {
|
||||
const newUnit = e.target.value;
|
||||
setUnit(newUnit);
|
||||
|
||||
// 如果已有结果,重新计算
|
||||
if (result) {
|
||||
setResult(performConversion(dateValue, selectedZone, newUnit) || '');
|
||||
}
|
||||
@@ -109,77 +81,79 @@ export function DatetimeToTimestamp() {
|
||||
[dateValue, selectedZone, result, performConversion],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="datetime-converter">
|
||||
<h2 className="converter-title">日期时间转时间戳</h2>
|
||||
const handleZoneChange = useCallback((e: SelectChangeEvent<string>) => {
|
||||
setSelectedZone(e.target.value);
|
||||
}, []);
|
||||
|
||||
<div className="converter-form">
|
||||
<div className="input-group">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="输入日期时间 (如: 2024-01-01 12:00:00)"
|
||||
return (
|
||||
<Paper elevation={3} sx={{ p: 2, my: 2, borderRadius: 2 }}>
|
||||
<Typography variant="h6" component="h2" align="center" gutterBottom>
|
||||
日期时间转时间戳
|
||||
</Typography>
|
||||
<Stack spacing={2} sx={{ mt: 2 }}>
|
||||
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
|
||||
<TextField
|
||||
label="输入日期时间"
|
||||
value={dateValue}
|
||||
className="datetime-input"
|
||||
onChange={(e) => {
|
||||
setDateValue(e.target.value);
|
||||
if (error) setError('');
|
||||
}}
|
||||
aria-label="输入要转换的日期时间"
|
||||
title="支持格式: YYYY-MM-DD HH:mm:ss"
|
||||
error={!!error}
|
||||
helperText={error || '格式: YYYY/MM/DD HH:mm:ss'}
|
||||
fullWidth
|
||||
variant="outlined"
|
||||
/>
|
||||
<select
|
||||
value={selectedZone}
|
||||
className="timezone-select"
|
||||
onChange={(e) => setSelectedZone(e.target.value)}
|
||||
aria-label="选择时区"
|
||||
>
|
||||
{TIME_ZONE_LIST.map((zone) => (
|
||||
<option key={zone} value={zone}>
|
||||
{zone}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<FormControl fullWidth>
|
||||
<InputLabel>时区</InputLabel>
|
||||
<Select
|
||||
value={selectedZone}
|
||||
label="时区"
|
||||
onChange={handleZoneChange}
|
||||
MenuProps={{ disableScrollLock: true }}
|
||||
>
|
||||
{TIME_ZONE_LIST.map((zone) => (
|
||||
<MenuItem key={zone} value={zone}>
|
||||
{zone}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Stack>
|
||||
|
||||
{error && (
|
||||
<div className="error-message" role="alert">
|
||||
⚠️ {error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="action-group">
|
||||
<button
|
||||
className="converter-btn action-btn"
|
||||
onClick={handleConvert}
|
||||
aria-label="转换日期时间为时间戳"
|
||||
>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center' }}>
|
||||
<Button variant="contained" size="medium" color="primary" onClick={handleConvert}>
|
||||
转换
|
||||
</button>
|
||||
</div>
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<div className="result-group">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="转换结果"
|
||||
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
|
||||
<TextField
|
||||
label="转换结果"
|
||||
value={result}
|
||||
className="result-input"
|
||||
readOnly
|
||||
aria-label="转换结果"
|
||||
fullWidth
|
||||
variant="outlined"
|
||||
InputProps={{
|
||||
readOnly: true,
|
||||
}}
|
||||
/>
|
||||
<select
|
||||
value={unit}
|
||||
className="unit-select"
|
||||
onChange={handleUnitChange}
|
||||
aria-label="选择时间戳单位"
|
||||
>
|
||||
{TIMESTAMP_UNITS.map(({ value, label }) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<FormControl fullWidth>
|
||||
<InputLabel>单位</InputLabel>
|
||||
<Select
|
||||
value={unit}
|
||||
label="单位"
|
||||
onChange={handleUnitChange}
|
||||
MenuProps={{ disableScrollLock: true }}
|
||||
>
|
||||
{TIMESTAMP_UNITS.map(({ value, label }) => (
|
||||
<MenuItem key={value} value={value}>
|
||||
{label}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Stack>
|
||||
</Stack>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { NavLink } from 'react-router-dom';
|
||||
import { useState, useEffect, ReactNode } from 'react';
|
||||
import { IconButton } from '@mui/material';
|
||||
import MenuIcon from '@mui/icons-material/Menu';
|
||||
import CloseIcon from '@mui/icons-material/Close';
|
||||
|
||||
interface RouteItem {
|
||||
path: string;
|
||||
@@ -76,16 +79,13 @@ function Navbar({ items = [] }: NavbarProps) {
|
||||
</NavLink>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
className="nav-toggle"
|
||||
<IconButton
|
||||
color="inherit"
|
||||
onClick={() => setIsMenuOpen(!isMenuOpen)}
|
||||
aria-label={isMenuOpen ? '收起菜单' : '展开菜单'}
|
||||
>
|
||||
<span className="nav-toggle-icon">{isMenuOpen ? '×' : '☰'}</span>
|
||||
{collapsedNavItems.length > 0 && !isMenuOpen && (
|
||||
<span className="nav-collapse-count">+{collapsedNavItems.length}</span>
|
||||
)}
|
||||
</button>
|
||||
{isMenuOpen ? <CloseIcon /> : <MenuIcon />}
|
||||
</IconButton>
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import CopyButton from './CopyButton';
|
||||
import { Button, Paper, Typography, Stack, Box } from '@mui/material';
|
||||
|
||||
/**
|
||||
* 时间戳显示和执行组件
|
||||
@@ -13,109 +14,110 @@ import CopyButton from './CopyButton';
|
||||
* @returns {JSX.Element} 时间戳组件
|
||||
*/
|
||||
export function TimestampExecution() {
|
||||
/** @type {[number, function]} 当前时间戳(毫秒)和更新函数 */
|
||||
const [currentTimestamp, setCurrentTimestamp] = useState(() => Math.floor(Date.now()));
|
||||
|
||||
/** @type {[boolean, function]} 是否显示毫秒(true=毫秒,false=秒) */
|
||||
const [currentTimestamp, setCurrentTimestamp] = useState(() =>
|
||||
Math.floor(Date.now()),
|
||||
);
|
||||
const [showMilliseconds, setShowMilliseconds] = useState(true);
|
||||
|
||||
/** @type {[boolean, function]} 时间戳是否正在自动更新 */
|
||||
const [isRunningTimestamp, setIsRunningTimestamp] = useState(true);
|
||||
|
||||
/**
|
||||
* 计算显示的时间戳值
|
||||
* @type {number}
|
||||
*/
|
||||
const displayTimestamp = showMilliseconds
|
||||
? currentTimestamp
|
||||
: Math.floor(currentTimestamp / 1000);
|
||||
|
||||
const unitText = showMilliseconds ? '毫秒' : '秒';
|
||||
|
||||
/**
|
||||
* 定时更新时间戳的副作用
|
||||
* 根据 isRunningTimestamp 和 showMilliseconds 控制定时器的启停和间隔
|
||||
*/
|
||||
useEffect(() => {
|
||||
let timer: number;
|
||||
|
||||
if (isRunningTimestamp) {
|
||||
const interval = showMilliseconds ? 100 : 1000;
|
||||
timer = window.setInterval(() => {
|
||||
setCurrentTimestamp(Math.floor(Date.now()));
|
||||
}, interval);
|
||||
}
|
||||
|
||||
// 清理函数
|
||||
return () => clearInterval(timer);
|
||||
}, [isRunningTimestamp, showMilliseconds]);
|
||||
|
||||
/**
|
||||
* 切换时间戳显示单位(毫秒/秒)
|
||||
*/
|
||||
const toggleUnit = useCallback(() => {
|
||||
setShowMilliseconds((prev) => !prev);
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 切换时间戳自动更新状态(启动/停止)
|
||||
*/
|
||||
const toggleTimestamp = useCallback(() => {
|
||||
setIsRunningTimestamp((prev) => !prev);
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 切换单位按钮的辅助文本
|
||||
* @type {string}
|
||||
*/
|
||||
const unitButtonLabel = showMilliseconds ? '切换为秒显示' : '切换为毫秒显示';
|
||||
|
||||
/**
|
||||
* 启动/停止按钮的辅助文本
|
||||
* @type {string}
|
||||
*/
|
||||
const toggleButtonLabel = isRunningTimestamp ? '停止时间戳自动更新' : '开始时间戳自动更新';
|
||||
|
||||
/**
|
||||
* 启动/停止按钮的显示文本
|
||||
* @type {string}
|
||||
*/
|
||||
const unitButtonLabel = showMilliseconds
|
||||
? '切换为秒显示'
|
||||
: '切换为毫秒显示';
|
||||
const toggleButtonLabel = isRunningTimestamp
|
||||
? '停止时间戳自动更新'
|
||||
: '开始时间戳自动更新';
|
||||
const toggleButtonText = isRunningTimestamp ? '停止' : '开始';
|
||||
|
||||
return (
|
||||
<div className="timestamp-container">
|
||||
<div className="timestamp-display">
|
||||
<span className="timestamp-value">{displayTimestamp}</span>
|
||||
<span className="timestamp-unit">{unitText}</span>
|
||||
</div>
|
||||
<Paper
|
||||
elevation={3}
|
||||
sx={{ p: 2, my: 2, borderRadius: 2, minWidth: 320, textAlign: 'center' }}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
alignItems: 'baseline',
|
||||
justifyContent: 'center',
|
||||
gap: 1,
|
||||
mb: 2,
|
||||
overflowX: 'auto',
|
||||
pb: 1,
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
variant="h4"
|
||||
component="span"
|
||||
sx={{
|
||||
fontFamily: 'monospace',
|
||||
fontWeight: 'bold',
|
||||
color: 'primary.main',
|
||||
whiteSpace: 'nowrap',
|
||||
}}
|
||||
>
|
||||
{displayTimestamp}
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="h6"
|
||||
component="span"
|
||||
sx={{ color: 'text.secondary', whiteSpace: 'nowrap' }}
|
||||
>
|
||||
{unitText}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<div className="timestamp-controls">
|
||||
<button
|
||||
type="button"
|
||||
className="action-btn"
|
||||
<Stack direction="row" spacing={2} justifyContent="center" flexWrap="wrap">
|
||||
<Button
|
||||
variant="contained"
|
||||
color="secondary"
|
||||
onClick={toggleUnit}
|
||||
aria-label={unitButtonLabel}
|
||||
title={unitButtonLabel}
|
||||
>
|
||||
切换单位
|
||||
</button>
|
||||
</Button>
|
||||
|
||||
<CopyButton
|
||||
text={String(currentTimestamp)}
|
||||
buttonText="复制时间戳"
|
||||
textToCopy={String(currentTimestamp)}
|
||||
buttonText="复制"
|
||||
aria-label="复制当前时间戳到剪贴板"
|
||||
color="primary"
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className={`${isRunningTimestamp ? 'stop-btn' : 'action-btn'}`}
|
||||
<Button
|
||||
variant="contained"
|
||||
color={isRunningTimestamp ? 'error' : 'primary'}
|
||||
onClick={toggleTimestamp}
|
||||
aria-label={toggleButtonLabel}
|
||||
title={toggleButtonLabel}
|
||||
>
|
||||
{toggleButtonText}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Button>
|
||||
</Stack>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,19 +1,24 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import dayjs from 'dayjs';
|
||||
import {
|
||||
Button,
|
||||
TextField,
|
||||
Select,
|
||||
MenuItem,
|
||||
FormControl,
|
||||
InputLabel,
|
||||
Paper,
|
||||
Typography,
|
||||
Stack,
|
||||
Box,
|
||||
SelectChangeEvent,
|
||||
} from '@mui/material';
|
||||
import utc from 'dayjs/plugin/utc';
|
||||
import timezone from 'dayjs/plugin/timezone';
|
||||
|
||||
/**
|
||||
* 时间戳转日期时间组件
|
||||
*
|
||||
* 功能特性:
|
||||
* 1. 将时间戳转换为日期时间字符串
|
||||
* 2. 支持多种时区选择
|
||||
* 3. 支持毫秒和秒单位切换
|
||||
* 4. 提供输入验证和错误提示
|
||||
* ```
|
||||
*
|
||||
* @returns {JSX.Element} 时间戳转日期时间组件
|
||||
*/
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezone);
|
||||
|
||||
// 常用时区列表
|
||||
const TIME_ZONE_LIST = [
|
||||
'America/New_York',
|
||||
'America/Chicago',
|
||||
@@ -35,10 +40,9 @@ const TIME_ZONE_LIST = [
|
||||
'Pacific/Auckland',
|
||||
];
|
||||
|
||||
// 时间戳单位选项
|
||||
const TIMESTAMP_UNITS = [
|
||||
{ value: 'milliseconds', label: '毫秒(ms)' },
|
||||
{ value: 'seconds', label: '秒(s)' },
|
||||
{ value: 'milliseconds', label: '毫秒 (ms)' },
|
||||
{ value: 'seconds', label: '秒 (s)' },
|
||||
];
|
||||
|
||||
export function TimestampToDatetime() {
|
||||
@@ -48,136 +52,129 @@ export function TimestampToDatetime() {
|
||||
const [selectedZone, setSelectedZone] = useState('Asia/Shanghai');
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const performConversion = useCallback(
|
||||
(timestampValue: string, selectedZone: string, unit: string) => {
|
||||
if (!timestampValue || timestampValue.trim() === '') {
|
||||
setError('请输入有效的日期时间');
|
||||
return '';
|
||||
}
|
||||
|
||||
try {
|
||||
const numberValue = Number(timestampValue);
|
||||
if (isNaN(numberValue)) {
|
||||
setError('时间戳必须是数字');
|
||||
return '';
|
||||
}
|
||||
|
||||
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 performConversion = useCallback((val: string, zone: string, u: string) => {
|
||||
if (!val || val.trim() === '') {
|
||||
setError('请输入有效的时间戳');
|
||||
return '';
|
||||
}
|
||||
const numberValue = Number(val);
|
||||
if (isNaN(numberValue)) {
|
||||
setError('时间戳必须是数字');
|
||||
return '';
|
||||
}
|
||||
const d = u === 'milliseconds' ? dayjs(numberValue) : dayjs.unix(numberValue);
|
||||
if (!d.isValid()) {
|
||||
setError('无效的时间戳格式');
|
||||
return '';
|
||||
}
|
||||
setError('');
|
||||
return d.tz(zone).format('YYYY/MM/DD HH:mm:ss');
|
||||
}, []);
|
||||
|
||||
const handleConvert = useCallback(() => {
|
||||
const newResult = performConversion(timestampValue, selectedZone, unit);
|
||||
setTimestampResult(newResult);
|
||||
}, [timestampValue, selectedZone, unit, performConversion]);
|
||||
|
||||
/**
|
||||
* 处理时间戳输入变化
|
||||
*/
|
||||
const handleInputChange = useCallback((e) => {
|
||||
setTimestampValue(e.target.value);
|
||||
setError(''); // 清除错误信息
|
||||
}, []);
|
||||
const handleInputChange = useCallback(
|
||||
(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setTimestampValue(e.target.value);
|
||||
if (error) setError('');
|
||||
},
|
||||
[error],
|
||||
);
|
||||
|
||||
/**
|
||||
* 处理时区选择变化
|
||||
*/
|
||||
const handleZoneChange = useCallback((e: React.ChangeEvent<HTMLSelectElement>) => {
|
||||
const newZone = e.target.value;
|
||||
setSelectedZone(newZone);
|
||||
}, []);
|
||||
const handleZoneChange = useCallback(
|
||||
(e: SelectChangeEvent<string>) => {
|
||||
const newZone = e.target.value;
|
||||
setSelectedZone(newZone);
|
||||
if (timestampResult) {
|
||||
const newResult = performConversion(timestampValue, newZone, unit);
|
||||
setTimestampResult(newResult || '');
|
||||
}
|
||||
},
|
||||
[performConversion, timestampResult, timestampValue, unit],
|
||||
);
|
||||
|
||||
/**
|
||||
* 处理时间戳单位变化
|
||||
*/
|
||||
const handleUnitChange = useCallback((e: React.ChangeEvent<HTMLSelectElement>) => {
|
||||
const newUnit = e.target.value;
|
||||
setUnit(newUnit);
|
||||
}, []);
|
||||
const handleUnitChange = useCallback(
|
||||
(e: SelectChangeEvent<string>) => {
|
||||
const newUnit = e.target.value;
|
||||
setUnit(newUnit);
|
||||
if (timestampResult) {
|
||||
const newResult = performConversion(timestampValue, selectedZone, newUnit);
|
||||
setTimestampResult(newResult || '');
|
||||
}
|
||||
},
|
||||
[performConversion, timestampResult, timestampValue, selectedZone],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="datetime-converter">
|
||||
<h2 className="converter-title">时间戳转日期时间</h2>
|
||||
|
||||
<div className="converter-form">
|
||||
<div className="input-group">
|
||||
<input
|
||||
type="number"
|
||||
placeholder="输入时间戳 (如: 1704067200000)"
|
||||
<Paper elevation={3} sx={{ p: 2, my: 2, borderRadius: 2 }}>
|
||||
<Typography variant="h6" component="h2" align="center" gutterBottom>
|
||||
时间戳转日期时间
|
||||
</Typography>
|
||||
<Stack spacing={2} sx={{ mt: 2 }}>
|
||||
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
|
||||
<TextField
|
||||
label="输入时间戳"
|
||||
placeholder="如: 1704067200000"
|
||||
value={timestampValue}
|
||||
className="datetime-input"
|
||||
onChange={handleInputChange}
|
||||
aria-label="输入要转换的时间戳"
|
||||
title="支持毫秒或秒为单位的时间戳"
|
||||
error={!!error}
|
||||
helperText={error}
|
||||
fullWidth
|
||||
variant="outlined"
|
||||
/>
|
||||
<select
|
||||
value={unit}
|
||||
className="unit-select"
|
||||
onChange={handleUnitChange}
|
||||
aria-label="选择时间戳单位"
|
||||
>
|
||||
{TIMESTAMP_UNITS.map(({ value, label }) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<FormControl fullWidth>
|
||||
<InputLabel>单位</InputLabel>
|
||||
<Select
|
||||
value={unit}
|
||||
label="单位"
|
||||
onChange={handleUnitChange}
|
||||
MenuProps={{ disableScrollLock: true }}
|
||||
>
|
||||
{TIMESTAMP_UNITS.map(({ value, label }) => (
|
||||
<MenuItem key={value} value={value}>
|
||||
{label}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Stack>
|
||||
|
||||
{error && (
|
||||
<div className="error-message" role="alert">
|
||||
⚠️ {error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="action-group">
|
||||
<button
|
||||
className="converter-btn action-btn"
|
||||
onClick={handleConvert}
|
||||
aria-label="转换时间戳为日期时间"
|
||||
>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center' }}>
|
||||
<Button variant="contained" size="medium" color="primary" onClick={handleConvert}>
|
||||
转换
|
||||
</button>
|
||||
</div>
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<div className="result-group">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="转换结果"
|
||||
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
|
||||
<TextField
|
||||
label="转换结果"
|
||||
value={timestampResult}
|
||||
className="result-input"
|
||||
readOnly
|
||||
aria-label="转换结果"
|
||||
fullWidth
|
||||
variant="outlined"
|
||||
InputProps={{
|
||||
readOnly: true,
|
||||
}}
|
||||
/>
|
||||
<select
|
||||
value={selectedZone}
|
||||
className="timezone-select"
|
||||
onChange={handleZoneChange}
|
||||
aria-label="选择时区"
|
||||
>
|
||||
{TIME_ZONE_LIST.map((zone) => (
|
||||
<option key={zone} value={zone}>
|
||||
{zone}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<FormControl fullWidth>
|
||||
<InputLabel>时区</InputLabel>
|
||||
<Select
|
||||
value={selectedZone}
|
||||
label="时区"
|
||||
onChange={handleZoneChange}
|
||||
MenuProps={{ disableScrollLock: true }}
|
||||
>
|
||||
{TIME_ZONE_LIST.map((zone) => (
|
||||
<MenuItem key={zone} value={zone}>
|
||||
{zone}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Stack>
|
||||
</Stack>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user