🚀 DAY 5 OF LAUNCH WEEK:Introducing Webhook Events for Alert Changes.Learn more
Socket
Book a DemoInstallSign in
Socket

timezone-converter-utils

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

timezone-converter-utils

A lightweight TypeScript library for converting dates between timezones using the Intl.DateTimeFormat API

latest
Source
npmnpm
Version
1.0.0
Version published
Maintainers
1
Created
Source

timezone-converter-utils

A lightweight TypeScript library for converting dates between timezones using the native Intl.DateTimeFormat API. Works seamlessly in both Node.js and browser environments (React, Next.js, Vue, etc.) without heavy dependencies.

Features

  • 🚀 Lightweight: Uses native Intl.DateTimeFormat API, no external dependencies
  • 🌍 Universal: Works in Node.js and all modern browsers
  • 📝 TypeScript: Full type definitions included
  • 🎯 Simple API: Easy to use with intuitive function signatures
  • 🕐 Flexible: Multiple output formats supported
  • Well-tested: Comprehensive test suite with Jest

Installation

npm install timezone-converter-utils
yarn add timezone-converter-utils
pnpm add timezone-converter-utils

Usage

Basic Usage

import { convertTime } from 'timezone-converter-utils';

// Convert from Pakistan time to New York time
const result = convertTime('2023-12-25 15:30:00', 'Asia/Karachi', 'America/New_York');
console.log(result); // "2023-12-25T05:30:00"

// Convert using Date object
const date = new Date('2023-12-25T15:30:00Z');
const converted = convertTime(date, 'UTC', 'Asia/Tokyo');
console.log(converted); // "2023-12-26T00:30:00"

CommonJS Usage

const { convertTime } = require('timezone-converter-utils');

const result = convertTime('2023-12-25 15:30:00', 'Asia/Karachi', 'America/New_York');
console.log(result);

Different Output Formats

import { convertTime } from 'timezone-converter-utils';

const date = '2023-12-25T15:30:00Z';
const fromZone = 'UTC';
const toZone = 'America/New_York';

// ISO format (default)
console.log(convertTime(date, fromZone, toZone));
// "2023-12-25T10:30:00"

// Short format
console.log(convertTime(date, fromZone, toZone, 'short'));
// "12/25/2023, 10:30 AM"

// Medium format
console.log(convertTime(date, fromZone, toZone, 'medium'));
// "Dec 25, 2023, 10:30:00 AM"

// Long format
console.log(convertTime(date, fromZone, toZone, 'long'));
// "December 25, 2023 at 10:30:00 AM EST"

// Full format
console.log(convertTime(date, fromZone, toZone, 'full'));
// "Monday, December 25, 2023 at 10:30:00 AM Eastern Standard Time"

// Custom locale
console.log(convertTime(date, fromZone, toZone, 'en-GB'));
// "25/12/2023, 15:30"

Additional Utilities

import { getCurrentTime, getTimezoneOffset, isValidTimezone } from 'timezone-converter-utils';

// Get current time in a specific timezone
const tokyoTime = getCurrentTime('Asia/Tokyo');
console.log(tokyoTime); // Current time in Tokyo

// Get timezone offset in minutes
const offset = getTimezoneOffset('America/New_York');
console.log(offset); // -300 (EST) or -240 (EDT)

// Validate timezone names
console.log(isValidTimezone('Asia/Karachi')); // true
console.log(isValidTimezone('Invalid/Zone')); // false

API Reference

convertTime(date, fromZone, toZone, format?)

Converts a date/time from one timezone to another.

Parameters:

  • date (string | Date): Input date as string or Date object
  • fromZone (string): Source timezone (IANA timezone name, e.g., "Asia/Karachi")
  • toZone (string): Target timezone (IANA timezone name, e.g., "America/New_York")
  • format (string, optional): Output format
    • 'iso' (default): ISO 8601 format
    • 'short': Short date and time format
    • 'medium': Medium date and time format
    • 'long': Long date and time format
    • 'full': Full date and time format
    • Custom locale string (e.g., 'en-US', 'fr-FR')

Returns: string - Formatted date string in the target timezone

Throws: TimezoneConversionError if any parameter is invalid

getCurrentTime(timezone, format?)

Gets the current time in a specific timezone.

Parameters:

  • timezone (string): Target timezone (IANA timezone name)
  • format (string, optional): Output format (same options as convertTime)

Returns: string - Current time formatted in the specified timezone

getTimezoneOffset(timezone, date?)

Gets the timezone offset in minutes for a specific timezone at a given date.

Parameters:

  • timezone (string): Target timezone (IANA timezone name)
  • date (string | Date, optional): Date to check offset for (defaults to current date)

Returns: number - Offset in minutes from UTC (negative = behind UTC, positive = ahead of UTC)

isValidTimezone(timezone)

Validates if a timezone string is a valid IANA timezone identifier.

Parameters:

  • timezone (string): Timezone string to validate

Returns: boolean - Whether the timezone is valid

Browser Compatibility

This library works in all modern browsers that support the Intl.DateTimeFormat API:

  • Chrome 24+
  • Firefox 29+
  • Safari 10+
  • Edge 12+
  • IE 11+

Framework Examples

React

import React, { useState, useEffect } from 'react';
import { convertTime, getCurrentTime } from 'timezone-converter-utils';

function TimeConverter() {
  const [currentTime, setCurrentTime] = useState('');

  useEffect(() => {
    const updateTime = () => {
      setCurrentTime(getCurrentTime('America/New_York', 'medium'));
    };

    updateTime();
    const interval = setInterval(updateTime, 1000);

    return () => clearInterval(interval);
  }, []);

  const handleConvert = () => {
    const converted = convertTime('2023-12-25 15:30:00', 'Asia/Karachi', 'America/New_York');
    console.log('Converted time:', converted);
  };

  return (
    <div>
      <p>Current NY Time: {currentTime}</p>
      <button onClick={handleConvert}>Convert Time</button>
    </div>
  );
}

Next.js

// pages/timezone.tsx
import { GetServerSideProps } from 'next';
import { convertTime } from 'timezone-converter-utils';

interface Props {
  serverTime: string;
  convertedTime: string;
}

export default function TimezonePage({ serverTime, convertedTime }: Props) {
  return (
    <div>
      <h1>Timezone Conversion</h1>
      <p>Server time (UTC): {serverTime}</p>
      <p>Converted to Tokyo: {convertedTime}</p>
    </div>
  );
}

export const getServerSideProps: GetServerSideProps = async () => {
  const now = new Date().toISOString();
  const convertedTime = convertTime(now, 'UTC', 'Asia/Tokyo', 'medium');

  return {
    props: {
      serverTime: now,
      convertedTime,
    },
  };
};

Vue 3

<template>
  <div>
    <h2>World Clock</h2>
    <div v-for="city in cities" :key="city.timezone">
      <strong>{{ city.name }}:</strong> {{ city.time }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { getCurrentTime } from 'timezone-converter-utils';

const cities = ref([
  { name: 'New York', timezone: 'America/New_York', time: '' },
  { name: 'London', timezone: 'Europe/London', time: '' },
  { name: 'Tokyo', timezone: 'Asia/Tokyo', time: '' },
  { name: 'Sydney', timezone: 'Australia/Sydney', time: '' },
]);

let interval: NodeJS.Timeout;

const updateTimes = () => {
  cities.value.forEach((city) => {
    city.time = getCurrentTime(city.timezone, 'medium');
  });
};

onMounted(() => {
  updateTimes();
  interval = setInterval(updateTimes, 1000);
});

onUnmounted(() => {
  if (interval) clearInterval(interval);
});
</script>

Common Timezone Names

Here are some commonly used IANA timezone identifiers:

RegionTimezoneDescription
AmericasAmerica/New_YorkEastern Time (US & Canada)
AmericasAmerica/ChicagoCentral Time (US & Canada)
AmericasAmerica/DenverMountain Time (US & Canada)
AmericasAmerica/Los_AngelesPacific Time (US & Canada)
AmericasAmerica/Sao_PauloBrasilia Time
EuropeEurope/LondonGreenwich Mean Time
EuropeEurope/ParisCentral European Time
EuropeEurope/BerlinCentral European Time
AsiaAsia/KarachiPakistan Standard Time
AsiaAsia/KolkataIndia Standard Time
AsiaAsia/ShanghaiChina Standard Time
AsiaAsia/TokyoJapan Standard Time
AsiaAsia/DubaiGulf Standard Time
AsiaAsia/SeoulKorea Standard Time
AustraliaAustralia/SydneyAustralian Eastern Time
AustraliaAustralia/MelbourneAustralian Eastern Time
PacificPacific/AucklandNew Zealand Standard Time
UTCUTCCoordinated Universal Time

Error Handling

The library throws TimezoneConversionError for invalid inputs:

import { convertTime, TimezoneConversionError } from 'timezone-converter-utils';

try {
  const result = convertTime('invalid-date', 'UTC', 'America/New_York');
} catch (error) {
  if (error instanceof TimezoneConversionError) {
    console.error('Timezone conversion failed:', error.message);
  }
}

TypeScript Support

Full TypeScript definitions are included:

import type { DateInput, TimezoneString } from 'timezone-converter-utils';

const date: DateInput = '2023-12-25T15:30:00Z';
const timezone: TimezoneString = 'America/New_York';

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT © [Your Name]

Changelog

1.0.0

  • Initial release
  • Core timezone conversion functionality
  • TypeScript support
  • Comprehensive test suite
  • Browser and Node.js compatibility

Keywords

timezone

FAQs

Package last updated on 04 Sep 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts