LocalTime.tsx 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use client';
  2. import { useEffect, useState } from 'react';
  3. import { useLanguage } from '@/lib/i18n/LanguageContext';
  4. import { formattingLocale } from '@/lib/i18n/config';
  5. interface LocalTimeProps {
  6. date: string | Date; // 接收 UTC 时间
  7. className?: string;
  8. options?: Intl.DateTimeFormatOptions;
  9. }
  10. export default function LocalTime({ date, className, options }: LocalTimeProps) {
  11. const { lang, t, localizedUI } = useLanguage();
  12. const [localTimeString, setLocalTimeString] = useState<string>('');
  13. useEffect(() => {
  14. if (!date) return;
  15. let dateObj: Date;
  16. // === 核心修复逻辑 ===
  17. if (typeof date === 'string') {
  18. // 1. 兼容 "YYYY-MM-DD HH:mm:ss" 格式,将空格替换为 T
  19. let normalizedDate = date.replace(' ', 'T');
  20. // 2. 如果字符串末尾没有 'Z' 且没有时区偏移(如 +08:00),强制追加 'Z'
  21. // 这告诉浏览器:“这个时间字符串是 UTC 时间”
  22. if (!normalizedDate.endsWith('Z') && !normalizedDate.includes('+')) {
  23. normalizedDate += 'Z';
  24. }
  25. dateObj = new Date(normalizedDate);
  26. } else {
  27. dateObj = date;
  28. }
  29. // 检查日期是否有效
  30. if (isNaN(dateObj.getTime())) {
  31. setLocalTimeString(localizedUI ? t('日期无效') : 'Invalid Date');
  32. return;
  33. }
  34. const locale = localizedUI ? formattingLocale(lang) : lang === 'zh' ? 'zh-CN' : 'en-US';
  35. const defaultOptions: Intl.DateTimeFormatOptions = {
  36. year: 'numeric',
  37. month: '2-digit',
  38. day: '2-digit',
  39. hour: '2-digit',
  40. minute: '2-digit',
  41. second: '2-digit',
  42. hour12: false,
  43. };
  44. const finalOptions = { ...defaultOptions, ...options };
  45. // 使用浏览器的 Intl API 进行本地化格式化 (会自动转换为用户时区)
  46. const formatter = new Intl.DateTimeFormat(locale, finalOptions);
  47. setLocalTimeString(formatter.format(dateObj));
  48. }, [date, lang, options, t, localizedUI]);
  49. if (!localTimeString) {
  50. return <span className={`opacity-0 ${className}`}>--:--</span>;
  51. }
  52. return <span className={className}>{localTimeString}</span>;
  53. }