date-fns Time Zone Utils

repository·main·Indexed 42 days ago

https://github.com/date-fns/tz

Time zone utilities for date-fns, featuring the TZDate and TZDateMini classes for performing date calculations in specific time zones rather than the system local time. Version 1.4.1 includes tools for calculating UTC offsets with tzOffset, retrieving time zone names via tzName, and scanning for offset changes with tzScan.

Tokens
6.3K
Snippets
27
Records
35
Agent score
50%

What's inside date-fns-tz

  1. Configure React Native / Hermes with Format.JS polyfills

    main

    To support the Hermes JS engine in React Native (starting from v1.3.0), you must import specific Format.JS polyfills in your application's entry point to ensure Intl support works correctly.

    import "@formatjs/intl-getcanonicallocales/polyfill";
    import "@formatjs/intl-locale/polyfill";
    import "@formatjs/intl-pluralrules/polyfill";
    import "@formatjs/intl-numberformat/polyfill";
    import "@formatjs/intl-numberformat/locale-data/en";
    import "@formatjs/intl-datetimeformat/polyfill";
    import "@formatjs/intl-datetimeformat/locale-data/en";
    import "@formatjs/intl-datetimeformat/add-golden-tz"; // or: "@formatjs/intl-datetimeformat/add-all-tz"
  2. Use TZDate and TZDateMini for time zone aware calculations

    main

    The package provides TZDate and TZDateMini extensions of the standard Date object. Unlike the native Date, these perform all calculations in a specified time zone rather than the system time zone. This is essential for handling Daylight Saving Time (DST) correctly across different regions or when rendering calendars/charts for specific users.

    Note: TZDate is a full implementation (1.2 kB) including formatter functions, while TZDateMini is a lightweight version (916 B) that only implements getters, setters, and getTimezoneOffset. Use TZDateMini for internal logic and TZDate if you need to expose formatted date strings.

    import { TZDate } from "@date-fns/tz";
    import { addHours } from "date-fns";
    
    // Using system time zone (e.g., America/Los_Angeles) during DST transition:
    const date = new Date(2022, 2, 13);
    addHours(date, 2).toString();
    //=> 'Sun Mar 13 2022 03:00:00 GMT-0700 (Pacific Daylight Time)'
    
    // Using Asia/Singapore provides the expected time regardless of system zone:
    const tzDate = new TZDate(2022, 2, 13, "Asia/Singapore");
    addHours(tzDate, 2).toString();
    //=> 'Sun Mar 13 2022 02:00:00 GMT+0800 (Singapore Standard Time)'
  3. Install @date-fns/tz

    main

    Install the package via npm to use TZDate and TZDateMini for time zone aware date calculations.

    npm install @date-fns/tz --save
  4. Use the TZDate class

    main

    The TZDate class is a time zone aware version of the standard Date class. It overrides original Date methods to perform calculations in a specific time zone.

    When used with date-fns, it behaves like the original Date class but respects the assigned time zone.

    Note on selection:

    • Use TZDate when you need to format strings or when working in environments you don't fully control (e.g., building a library).
    • Use TZDateMini (a lighter version) if you need a smaller build size and do not require the full suite of formatter functions.
  5. Install and verify the Time Zone Database (tz)

    main

    To install the Time Zone Database (tz, tzdb, or zoneinfo) on your system, you must first acquire the code and data from the IANA repository. After acquisition, you may need to modify the Makefile to suit your specific platform (especially if not using GNU/Linux).

    To install the database to a specific directory, use the make command with the TOPDIR variable, then verify the installation using zdump.

    # Install to a desired directory
    make TOPDIR="$HOME/tzdir" install
    
    # Verify the installation with zdump
    "$HOME/tzdir/usr/bin/zdump" -v America/Los_Angeles
  6. Get time zone UTC offset with tzOffset()

    main

    The tzOffset function returns the UTC offset in minutes for a given time zone and date.

    Note on Sign: Unlike Date.prototype.getTimezoneOffset(), tzOffset returns the value mirrored to the sign of the offset. For example, for UTC+8 (Asia/Singapore), tzOffset returns 480, whereas getTimezoneOffset returns -480.

    import { tzOffset } from "@date-fns/tz";
    
    const date = new Date("2020-01-15T00:00:00Z");
    
    tzOffset("Asia/Singapore", date); // 480
    tzOffset("America/New_York", date); // -300
  7. Scan time zone changes with tzScan()

    main

    The tzScan function scans a time zone for offset changes (like DST transitions) within a specific interval. It returns an array of objects containing the date of the change, the amount of change, and the new offset.

    import { tzScan } from "@date-fns/tz";
    
    tzScan("America/New_York", {
      start: new Date("2020-01-01T00:00:00Z"),
      end: new Date("2024-01-01T00:00:00Z"),
    });
    //=> [{ date: ..., change: 60, offset: -240 }, ...]
  8. Get human-readable time zone names with tzName()

    main

    The tzName function returns the time zone name in a human-readable format for a given date. You can specify the format using one of the following options:

    • "short": e.g., "EDT" or "GMT+8" (TR35 z..zzz)
    • "long": e.g., "Eastern Daylight Time" or "Singapore Standard Time" (TR35 zzzz)
    • "shortGeneric": e.g., "ET" or "Singapore Time" (TR35 v)
    • "longGeneric": e.g., "Eastern Time" or "Singapore Time" (TR35 vvvv)

    These correspond to Unicode TR35 tokens.

    import { tzName } from "@date-fns/tz";
    
    const date = new Date("2020-01-01T00:00:00.000Z");
    
    tzName("America/New_York", date, "short"); // "EST"
    tzName("America/New_York", date, "shortGeneric"); // "ET"
  9. TZDate API Reference

    main

    The TZDate class (and TZDateMini) allows creating date instances tied to a specific time zone.

    Constructor

    Mirrors the standard Date constructor but accepts an optional time zone as the last argument:

    • new TZDate(year, month, day, timeZone)
    • new TZDate(timestamp, timeZone)
    • new TZDate(dateString, timeZone)

    TZDate.tz()

    Static method to construct a TZDate instance with a specific time zone. Unlike the constructor, this method expects the time zone as the first argument:

    • TZDate.tz(timeZone)
    • TZDate.tz(timeZone, year, month)
    • TZDate.tz(timeZone, timestamp)
    • TZDate.tz(timeZone, dateString)

    timeZone

    Readonly property returning the assigned time zone name (e.g., "Asia/Singapore"). Returns undefined if no time zone was provided.

    withTimeZone(timeZone)

    Returns a new TZDate instance representing the same moment in time but in the specified timeZone.

    [Symbol.for("constructDateFrom")]

    Exposes a method to construct a standard Date instance in the same time zone. This is used by date-fns internally but can be accessed via import { constructFromSymbol } from "@date-fns/tz".

    import { TZDate, constructFromSymbol } from "@date-fns/tz";
    
    // Constructor
    const sg = new TZDate(2022, 2, 13, "Asia/Singapore");
    
    // TZDate.tz
    const nowInSg = TZDate.tz("Asia/Singapore");
    
    // timeZone property
    console.log(sg.timeZone); // "Asia/Singapore"
    
    // withTimeZone
    const ny = sg.withTimeZone("America/New_York");
    
    // constructDateFrom
    const symbol = Symbol.for("constructDateFrom");
    const date = sg[symbol](new Date(2024, 0, 1));
  10. Use tz() to provide time zone context to date-fns functions

    main

    Starting from date-fns@4, you can use the tz function from @date-fns/tz to specify the time zone context for date-fns utility functions via the in option.

    import { isSameDay } from "date-fns";
    import { tz } from "@date-fns/tz";
    
    isSameDay("2024-09-09T23:00:00-04:00", "2024-09-10T10:00:00+08:00", {
      in: tz("Europe/Prague"),
    });
    //=> true
  11. Accepted time zone formats

    main

    When initializing a TZDate, you can provide the time zone using IANA names or UTC offsets.

    // IANA name
    new TZDate(2022, 2, 13, "Asia/Singapore");
    
    // UTC offset (HH:mm)
    new TZDate(2022, 2, 13, "+08:00");
    
    // UTC offset (HHmm)
    new TZDate(2022, 2, 13, "-2359");
  12. Scan for time zone changes with tzScan()

    main

    The tzScan function identifies when a time zone's UTC offset changes within a specific time interval. It returns an array of TZChange objects, each representing a specific moment a change occurred, the magnitude of the change, and the resulting offset.

    Parameters

    • timeZone: A string representing the time zone name (IANA format) or a UTC offset.
    • interval: A TZChangeInterval object defining the start and end dates for the scan.

    Returns

    An array of TZChange objects.

    import { tzScan } from '@date-fns/tz';
    
    const changes = tzScan('America/New_York', {
      start: new Date('2024-03-01T00:00:00Z'),
      end: new Date('2024-04-01T00:00:00Z')
    });