# 时区

URL: https://caijiao.org/date-fns/general/time-zones
Source: docs/date-fns/general/time-zones.md
Description: 使用 UTC 或 ISO 日期字符串很容易，当所有时间都以用户的本地时间显示在浏览器中时，使用 JS 日期也是如此。 当使用除当前系统之外的另一个时区的本地时间时会遇到困难，例如在欧洲的节点服务器或用户的机器设置为 EST 上显示太平洋标准时间晚上 8 点在洛杉矶发生的事件的本地时间。

## 概述

使用 UTC 或 ISO 日期字符串很容易，当所有时间都以用户的本地时间显示在浏览器中时，使用 JS 日期也是如此。 当使用除当前系统之外的另一个时区的本地时间时会遇到困难，例如在欧洲的节点服务器或用户的机器设置为 EST 上显示太平洋标准时间晚上 8 点在洛杉矶发生的事件的本地时间。

在这种情况下，有两条相关信息：

- 时间戳、UTC 或 ISO 日期字符串形式的固定时间点，以及。

- 时区描述符，通常是偏移量或 IANA 时区名称（例如 `America/Los_Angeles`）。

Moment 和 Luxon 等库提供自己的日期时间类，在内部管理这些时间戳和时区值。 由于 date-fns 总是返回一个普通的 JS 日期，它隐含了当前系统的时区，因此需要辅助函数来处理与时区相关的常见用例。

## date-fns-tz

无依赖 IANA 时区支持是通过 [Intl API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl) 实现的，以将实际时区数据保留在代码包之外。 现代浏览器都支持[必要的功能](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat#Browser_compatibility)，对于那些不支持的浏览器，可以使用 polyfill。

提供了用于在 Date 实例之间进行转换的函数，该实例将调整内部 UTC 时间，以便在相关时区中打印为正确的时间值，而不管当前系统时区如何。 扩展了 date-fns 格式功能，支持 z...zzzz 标记以格式化长时区名称和短时区名称。

License: MIT

## 概要

```javascript
const { zonedTimeToUtc, utcToZonedTime, format } = require('date-fns-tz')

// Set the date to "2018-09-01T16:01:36.386Z"
const utcDate = zonedTimeToUtc('2018-09-01 18:01:36.386', 'Europe/Berlin')

// Obtain a Date instance that will render the equivalent Berlin time for the UTC date
const date = new Date('2018-09-01T16:01:36.386Z')
const timeZone = 'Europe/Berlin'
const zonedDate = utcToZonedTime(date, timeZone)
// zonedDate could be used to initialize a date picker or display the formatted local date/time

// Set the output to "1.9.2018 18:01:36.386 GMT+02:00 (CEST)"
const pattern = 'd.M.yyyy HH:mm:ss.SSS \'GMT\' XXX (z)'
const output = format(zonedDate, pattern, { timeZone: 'Europe/Berlin' })
```

## 链接

- [API / Usage Scenarios](https://github.com/marnusw/date-fns-tz#time-zone-helpers)
