UNPKG

2.8 kBMarkdownView Raw
1# Time Zones
2
3## Table of Contents
4
5- [Overview](#overview)
6
7- [`date-fns-tz`](#date-fns-tz)
8
9## Overview
10
11Working with UTC or ISO date strings is easy, and so is working with JS dates when all times
12are displayed in a user's local time in the browser. The difficulty comes when working with another
13time zone's local time, other than the current system's, like showing the local time of an event in LA
14at 8pm PST on a Node server in Europe or a user's machine set to EST.
15
16In this case there are two relevant pieces of information:
17 - a fixed moment in time in the form of a timestamp, UTC or ISO date string, and
18 - the time zone descriptor, usually an offset or IANA time zone name (e.g. `America/Los_Angeles`).
19
20Libraries like Moment and Luxon, which provide their own date time classes, manage these timestamp and time
21zone values internally. Since `date-fns` always returns a plain JS Date, which implicitly has the current
22system's time zone, helper functions are needed for handling common time zone related use cases.
23
24## [`date-fns-tz`](https://www.npmjs.com/package/date-fns-tz)
25
26Dependency free IANA time zone support is implemented via the
27[Intl API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl) to keep
28actual time zone data out of code bundles. Modern browsers all support the
29[necessary features](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat#Browser_compatibility),
30and for those that don't a [polyfill](https://github.com/yahoo/date-time-format-timezone) can be used.
31
32Functions are provided for converting to and from a Date instance which will have the internal UTC time
33adjusted so it prints to the correct time value in the associated time zone, regardless of the current
34system time zone. The `date-fns` `format` function is extended with support for the `z...zzzz` tokens to
35format long and short time zone names.
36
37Compatible with `date-fns` version 2
38
39License: MIT
40
41### Synopsis
42
43```js
44const { zonedTimeToUtc, utcToZonedTime, format } = require('date-fns-tz')
45
46// Set the date to "2018-09-01T16:01:36.386Z"
47const utcDate = zonedTimeToUtc('2018-09-01 18:01:36.386', 'Europe/Berlin')
48
49// Obtain a Date instance that will render the equivalent Berlin time for the UTC date
50const date = new Date('2018-09-01Z16:01:36.386Z')
51const timeZone = 'Europe/Berlin'
52const zonedDate = utcToZonedTime(date, timeZone)
53// zonedDate could be used to initialize a date picker or display the formatted local date/time
54
55// Set the output to "1.9.2018 18:01:36.386 GMT+02:00 (CEST)"
56const pattern = 'D.M.YYYY HH:mm:ss.SSS [GMT]Z (z)'
57const output = format(zonedDate, pattern, { timeZone })
58```
59
60### Links
61
62- [API / Usage Scenarios](https://github.com/marnusw/date-fns-tz#time-zone-helpers)