import React, { useState, useCallback } from 'react'; import dayjs from '@/utils/dayjs'; import { Button, TextField, Select, MenuItem, FormControl, InputLabel, Paper, Stack, Box, SelectChangeEvent, } from '@mui/material'; import { TIME_ZONE_LIST, TIMESTAMP_UNITS } from './constants'; export function TimestampToDatetime() { const [timestampValue, setTimestampValue] = useState(() => dayjs().valueOf().toString()); const [timestampResult, setTimestampResult] = useState(''); const [unit, setUnit] = useState('milliseconds'); const [selectedZone, setSelectedZone] = useState('Asia/Shanghai'); const [error, setError] = useState(''); 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: React.ChangeEvent) => { setTimestampValue(e.target.value); if (error) setError(''); }, [error], ); const handleZoneChange = useCallback( (e: SelectChangeEvent) => { 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: SelectChangeEvent) => { const newUnit = e.target.value; setUnit(newUnit); if (timestampResult) { const newResult = performConversion(timestampValue, selectedZone, newUnit); setTimestampResult(newResult || ''); } }, [performConversion, timestampResult, timestampValue, selectedZone], ); return ( 单位 时区 ); }