【React】 时区

68 阅读2分钟

在上家公司的工作经历中,我做的项目都是面向海外用户的保险产品,那么就会涉及到时区

标准

UTC(Coordinated Universal Time) 时间, 它是全球通用的时间标准

  • UTC 时间: 2025-03-10T12:00:00Z

z 表示 Zulu 时间,即 UTC 时间

格式

ISO 8601

2025-03-10T12:00:00Z(ISO 8601 格式, UTC 时间)
2025-03-10T11:58:52.886+00:00(ISO 8601 格式, UTC 时间)

UTC 时间的标志,必须是 Z 或者+00, 表示没有时区偏移。 如 2025-03-10T11:58:52.886+08:00,北京时间,比 UTC 时间晚 8 个小时,这个就并不是 UTC 时间,对应的 UTC 时间是

 UTC 时间 = 本地时间 - 时区偏移 =  11:58:52.886 - 8 小时 = 03:58:52.886

结果对应的 UTC 时间是 2025-03-10T03:58:52.886Z 或者 2025-03-10T03:58:52.886+00:00

  • 时间戳
// 1741699200
new Date('2025-03-10T12:00:00Z').getTime() / 1000

代码

  • 后端: 返回的是 UTC 时间格式
  • 前端: 需要根据对应的时区展示时间格式

前端实现框架有:dayjsdate-fnsLuxon

下面以date-fns为例, 假设后端返回的时间是 2025-03-10T13:20:21Z

展示时间

import { formatInTimeZone, getTimezoneOffset } from "date-fns-tz";

// 时区
const TIMEZONES = [
  "Asia/Shanghai",        // 中国上海
  "Asia/Tokyo",           // 日本东京
  "Europe/London",        // 英国伦敦
  "Europe/Paris",         // 法国巴黎
  "America/New_York",     // 美国纽约
  "America/Los_Angeles",  // 美国洛杉矶
  "Australia/Sydney",     // 澳大利亚悉尼
  "Pacific/Auckland"      // 新西兰奥克兰
];

// tz 是时区
const format =  (time:Date,tz:string, formatStr:string) =>{
   return formatInTDimeZone(time, tz, formatStr);
}
import { getTimezoneOffset } from "date-fns-tz";

 // 获取时区偏移量
  const getTimezoneOffsetString = (tz: string) => {
    const offsetMinutes = getTimezoneOffset(tz, new Date()) / 60000;
    const hours = Math.abs(Math.floor(offsetMinutes / 60));
    const minutes = Math.abs(Math.floor(offsetMinutes % 60));
    const sign = offsetMinutes >= 0 ? '+' : '-';
    return `${sign}${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
  };

如果是 Asia/Shanghai时区,那么

image.png

发送到后端, 在date-fns用的也是同一个方法

import { formatInTimeZone, getTimezoneOffset } from "date-fns-tz";

const formatInTimeZone => formatInTimeZone(currentTime, selectedTimezone, selectedFormat.format)

git 地址