timezone-converter-utils
v1.0.0
Published
A lightweight TypeScript library for converting dates between timezones using the Intl.DateTimeFormat API
Maintainers
Readme
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.DateTimeFormatAPI, 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-utilsyarn add timezone-converter-utilspnpm add timezone-converter-utilsUsage
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')); // falseAPI 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 objectfromZone(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 asconvertTime)
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:
| Region | Timezone | Description |
| --------- | --------------------- | --------------------------- |
| Americas | America/New_York | Eastern Time (US & Canada) |
| Americas | America/Chicago | Central Time (US & Canada) |
| Americas | America/Denver | Mountain Time (US & Canada) |
| Americas | America/Los_Angeles | Pacific Time (US & Canada) |
| Americas | America/Sao_Paulo | Brasilia Time |
| Europe | Europe/London | Greenwich Mean Time |
| Europe | Europe/Paris | Central European Time |
| Europe | Europe/Berlin | Central European Time |
| Asia | Asia/Karachi | Pakistan Standard Time |
| Asia | Asia/Kolkata | India Standard Time |
| Asia | Asia/Shanghai | China Standard Time |
| Asia | Asia/Tokyo | Japan Standard Time |
| Asia | Asia/Dubai | Gulf Standard Time |
| Asia | Asia/Seoul | Korea Standard Time |
| Australia | Australia/Sydney | Australian Eastern Time |
| Australia | Australia/Melbourne | Australian Eastern Time |
| Pacific | Pacific/Auckland | New Zealand Standard Time |
| UTC | UTC | Coordinated 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
