or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

date-parsing.mdformatting.mdfunctional-programming.mdindex.mdtimezone-conversion.md
tile.json

timezone-conversion.mddocs/

Timezone Conversion

Functions for converting dates between timezones and obtaining timezone offset information, with proper handling of Daylight Saving Time transitions.

Capabilities

toZonedTime Function

Convert a UTC date to represent local time in a specific timezone. The returned Date object will have values that represent the local time in the target timezone.

/**
 * Get a date representing local time in a given timezone from UTC date
 * @param date - Date with UTC time
 * @param timeZone - IANA time zone identifier or offset string
 * @param options - Parsing options
 * @returns Date instance with values representing local time in the target timezone
 */
function toZonedTime(
  date: Date | string | number,
  timeZone: string,
  options?: ToDateOptionsWithTZ
): Date;

Usage Examples:

import { toZonedTime } from "date-fns-tz";

const utcDate = new Date('2024-01-15T10:30:00.000Z');

// Convert to New York time
const nyTime = toZonedTime(utcDate, 'America/New_York');
console.log(nyTime.getHours()); // 5 (represents 5:30 AM in NY)
console.log(nyTime.getMinutes()); // 30

// Convert to Tokyo time
const tokyoTime = toZonedTime(utcDate, 'Asia/Tokyo');
console.log(tokyoTime.getHours()); // 19 (represents 7:30 PM in Tokyo)

// Using offset string
const indiaTime = toZonedTime(utcDate, '+05:30');
console.log(indiaTime.getHours()); // 16 (represents 4:00 PM in India)

// The returned date object represents local time, not UTC
console.log(nyTime.toISOString()); // This shows the offset applied to UTC

fromZonedTime Function

Convert a date representing local time in a timezone back to UTC. This is the reverse operation of toZonedTime.

/**
 * Get UTC date/time from a date representing local time in a given timezone
 * @param date - Date with values representing local time
 * @param timeZone - IANA time zone identifier or offset string
 * @param options - Parsing options
 * @returns Date instance with equivalent UTC time
 */
function fromZonedTime(
  date: Date | string | number,
  timeZone: string,
  options?: ToDateOptionsWithTZ
): Date;

Usage Examples:

import { fromZonedTime, toZonedTime } from "date-fns-tz";

// Create a date representing 2:30 PM in New York
const localDate = new Date(2024, 0, 15, 14, 30, 0); // Note: month is 0-indexed

// Convert to UTC
const utcDate = fromZonedTime(localDate, 'America/New_York');
console.log(utcDate.toISOString()); // "2024-01-15T19:30:00.000Z"

// Round-trip conversion
const originalUtc = new Date('2024-01-15T10:30:00Z');
const zoned = toZonedTime(originalUtc, 'Europe/London');
const backToUtc = fromZonedTime(zoned, 'Europe/London');
console.log(backToUtc.toISOString()); // "2024-01-15T10:30:00.000Z"

// Working with user input (local time)
const userInput = new Date('2024-07-15T14:30:00'); // User enters local time
const utcFromLocal = fromZonedTime(userInput, 'America/Los_Angeles');
console.log(utcFromLocal.toISOString()); // "2024-07-15T21:30:00.000Z"

getTimezoneOffset Function

Get the offset in milliseconds between a timezone and UTC at a specific date, accounting for Daylight Saving Time.

/**
 * Get offset in milliseconds between timezone and UTC
 * @param timeZone - IANA time zone identifier or offset string
 * @param date - Optional date for DST calculations (defaults to current date)
 * @returns Offset in milliseconds (positive for timezones ahead of UTC)
 */
function getTimezoneOffset(timeZone: string, date?: Date | number): number;

Usage Examples:

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

// Get current offset for different timezones
const nyOffset = getTimezoneOffset('America/New_York');
console.log(nyOffset); // -18000000 (-5 hours in ms) during EST

const tokyoOffset = getTimezoneOffset('Asia/Tokyo');
console.log(tokyoOffset); // 32400000 (+9 hours in ms)

// Check offset at specific dates (for DST)
const winterDate = new Date('2024-01-15');
const summerDate = new Date('2024-07-15');

const nyWinterOffset = getTimezoneOffset('America/New_York', winterDate);
console.log(nyWinterOffset / 1000 / 60 / 60); // -5 (EST)

const nySummerOffset = getTimezoneOffset('America/New_York', summerDate);
console.log(nySummerOffset / 1000 / 60 / 60); // -4 (EDT)

// Using with offset strings
const fixedOffset = getTimezoneOffset('+05:30');
console.log(fixedOffset); // 19800000 (+5.5 hours in ms)

// Convert to hours for readability
function offsetToHours(offsetMs: number): number {
  return offsetMs / 1000 / 60 / 60;
}

console.log(offsetToHours(getTimezoneOffset('Europe/Berlin'))); // 1 or 2 depending on DST

Options Interface

interface ToDateOptionsWithTZ {
  /** IANA time zone identifier or offset string */
  timeZone?: string;
  /** Number of additional digits for extended year representation */
  additionalDigits?: 0 | 1 | 2;
}

Practical Use Cases

Converting Server Time to User Timezone

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

// Server returns UTC timestamp
const serverTimestamp = new Date('2024-01-15T10:30:00Z');
const userTimezone = 'America/Los_Angeles';

// Method 1: Convert then format with regular date-fns
const userLocalTime = toZonedTime(serverTimestamp, userTimezone);
// Now format with regular date-fns format function

// Method 2: Format directly in user timezone
const formatted = formatInTimeZone(serverTimestamp, userTimezone, 'PPpp');
console.log(formatted); // "Jan 15, 2024 at 2:30:00 AM"

Handling User Form Input

import { fromZonedTime } from "date-fns-tz";

// User selects date/time in their local timezone
const userSelectedDate = new Date('2024-01-15T14:30:00');
const userTimezone = 'Europe/Paris';

// Convert to UTC for storage
const utcForStorage = fromZonedTime(userSelectedDate, userTimezone);
console.log(utcForStorage.toISOString()); // "2024-01-15T13:30:00.000Z"

Timezone-Aware Scheduling

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

// Schedule a meeting at 3 PM in New York
const meetingTimeNY = new Date(2024, 0, 15, 15, 0, 0); // 3 PM local
const nyTimezone = 'America/New_York';
const londonTimezone = 'Europe/London';

// Convert to UTC
const meetingUTC = fromZonedTime(meetingTimeNY, nyTimezone);

// What time is the meeting in London?
const meetingTimeLondon = toZonedTime(meetingUTC, londonTimezone);
console.log(meetingTimeLondon.getHours()); // 20 (8 PM in London)

// Check timezone differences
const nyOffset = getTimezoneOffset(nyTimezone, meetingUTC);
const londonOffset = getTimezoneOffset(londonTimezone, meetingUTC);
const timeDifference = (londonOffset - nyOffset) / 1000 / 60 / 60;
console.log(`London is ${timeDifference} hours ahead of New York`);

DST Handling Examples

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

const timezone = 'America/New_York';

// Spring forward (DST begins)
const beforeDST = new Date('2024-03-10T06:00:00Z'); // 1 AM EST
const duringDST = new Date('2024-03-10T08:00:00Z'); // 4 AM EDT (after 2 AM jump)

console.log(getTimezoneOffset(timezone, beforeDST) / 1000 / 60 / 60); // -5 (EST)
console.log(getTimezoneOffset(timezone, duringDST) / 1000 / 60 / 60); // -4 (EDT)

// Fall back (DST ends)
const beforeFallBack = new Date('2024-11-03T05:00:00Z'); // 1 AM EDT
const afterFallBack = new Date('2024-11-03T07:00:00Z'); // 2 AM EST (after 2 AM repeat)

console.log(getTimezoneOffset(timezone, beforeFallBack) / 1000 / 60 / 60); // -4 (EDT)
console.log(getTimezoneOffset(timezone, afterFallBack) / 1000 / 60 / 60); // -5 (EST)

Working with Offset Strings

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

const utcDate = new Date('2024-01-15T10:30:00Z');

// Various offset formats supported
const formats = [
  '+05:30',    // India Standard Time
  '+0530',     // Alternative format
  '+05',       // Hour only
  '-08:00',    // Pacific Standard Time
  '-0800',     // Alternative format
  'Z'          // UTC
];

formats.forEach(offset => {
  const converted = toZonedTime(utcDate, offset);
  console.log(`${offset}: ${converted.getHours()}:${converted.getMinutes()}`);
});

// Offset strings work with all functions
const offsetMs = getTimezoneOffset('+05:30');
console.log(offsetMs / 1000 / 60); // 330 minutes

Error Handling

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

// Invalid timezone identifiers throw RangeError
try {
  toZonedTime(new Date(), 'Invalid/Timezone');
} catch (error) {
  console.log(error instanceof RangeError); // true
}

// Invalid dates return Invalid Date
const invalidResult = toZonedTime(new Date('invalid'), 'UTC');
console.log(invalidResult.toString()); // "Invalid Date"

// Check for valid dates
function isValidDate(date: Date): boolean {
  return !isNaN(date.getTime());
}

const result = toZonedTime(new Date('2024-01-15'), 'America/New_York');
if (isValidDate(result)) {
  console.log('Conversion successful');
}