date-fns Time Zone Support

3.2.0 · active · verified Tue Apr 21

date-fns-tz provides robust time zone functionality for date-fns v3 and v4, leveraging the browser's native `Intl` API to avoid bundling large time zone data files. The current stable version is 3.2.0. This library is designed to work seamlessly with `date-fns`'s immutable `Date` object approach, offering functions like `formatInTimeZone` to format dates in a specified IANA time zone, and conversion utilities such as `toZonedTime` and `fromZonedTime` for shifting dates between UTC and specific time zones. It is a peer dependency of `date-fns`, requiring a compatible version (`^3.0.0 || ^4.0.0`). Its release cadence is tied to major `date-fns` versions, with minor updates for features and bug fixes. Key differentiators include its lightweight nature due to `Intl` API reliance and its adherence to the `date-fns` philosophy of pure functions and native Date objects.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing a UTC date string, then formatting it directly in a specific IANA time zone using `formatInTimeZone`, and converting it to a 'local' date in that time zone using `toZonedTime` for further processing with `date-fns`.

import { formatInTimeZone, toZonedTime } from 'date-fns-tz';
import { parseISO, format } from 'date-fns';

const dateString = '2024-04-21T18:30:00Z'; // UTC date string
const timeZone = 'America/Los_Angeles';

// Parse the ISO string to a Date object (which will be in UTC internally)
const utcDate = parseISO(dateString);

// Format the UTC date directly into the target timezone
const formattedTimeInLA = formatInTimeZone(utcDate, timeZone, 'yyyy-MM-dd HH:mm:ss zzz');

// Convert the UTC date to a Zoned Date object (representing local time in LA)
const zonedDateInLA = toZonedTime(utcDate, timeZone);

// Format the zoned date using date-fns's format (since it's now a 'local' date in LA)
const formattedZonedDate = format(zonedDateInLA, 'yyyy-MM-dd HH:mm:ss');

console.log(`Original UTC: ${dateString}`);
console.log(`Formatted in ${timeZone} (with timezone token): ${formattedTimeInLA}`);
console.log(`Zoned Date in ${timeZone}: ${zonedDateInLA.toISOString()}`); // Shows as if local time, but internally still UTC
console.log(`Formatted Zoned Date in ${timeZone}: ${formattedZonedDate}`);

view raw JSON →