@countrystatecity/timezones

中文文档
2.0.2发布于 2026/11/03ODbL-1.0TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 2655

Comprehensive timezone data with conversion utilities and iOS/Safari support

原始使用文档
文档目录24 节
  1. Upgrading to 2.0.0
  2. ✨ Features
  3. 📦 Installation
  4. 🚀 Quick Start
  5. Local package or live API?
  6. 📖 API Reference
  7. Core Functions
  8. Utility Functions
  9. 🌍 Real-World Examples
  10. Meeting Scheduler
  11. World Clock
  12. DST Reminder
  13. 🔧 TypeScript Types
  14. 📊 Bundle Size
  15. Data Coverage
  16. 🧪 Testing
  17. 🔄 CI/CD & Automation
  18. Continuous Integration
  19. Automated Data Updates
  20. Automated Publishing
  21. 📄 License
  22. 🤝 Contributing
  23. 📦 Package Ecosystem
  24. 🔗 Links

@countrystatecity/timezones

npm CI npm downloads npm downloads

Comprehensive timezone data with conversion utilities and iOS/Safari support.

Environment: 🖥️ Server-side only (Node.js, Next.js API routes, Express, etc.)

Upgrading to 2.0.0

The v4.0-export.50 snapshot corrects timezone offsets and abbreviations. All 432 IANA zone records remain, but abbreviation lookups for ACDT, AEDT, ALMT, EASST, EGT, MIST, MSD+1, NZDT, QYZST, QYZT, and WEST now return no matches. Abbreviations CLT, EAST, KZT, and NZST were added. Persist IANA zone names and refresh abbreviation/offset metadata before upgrading.

This package does not contain city/state ids. If you combine it with geographic packages, the upstream v4.0 release documents removed geographic ids and provides removed_ids_v3.2_to_v4.0.csv for migrating stored city/state ids.

✨ Features

  • 🌐 426 distinct IANA names: 432 country/zone records in this snapshot
  • 🗺️ 250 Countries: Timezones organized by country
  • 🔄 Time Conversion: Convert between timezones easily
  • ⏰ Current Time: Get current time in any timezone
  • 📅 DST Support: Detect daylight saving time
  • 📱 iOS Compatible: No stack overflow errors on Safari/iOS
  • 🚀 Minimal Bundle: <20KB initial load with lazy loading
  • 📝 TypeScript: Full type definitions included
  • 🔧 Tree-Shakeable: Only bundle what you use

📦 Installation

npm install @countrystatecity/timezones
# or
yarn add @countrystatecity/timezones
# or
pnpm add @countrystatecity/timezones

🚀 Quick Start

import {
  getTimezones,
  getTimezonesByCountry,
  convertTime,
  getCurrentTime
} from '@countrystatecity/timezones';

// Get all timezones (~74KB - lazy loaded)
const timezones = await getTimezones();
console.log(timezones.length); // 432 country/zone records

// Get timezones for a specific country (~0.3KB per country)
const usTimezones = await getTimezonesByCountry('US');
console.log(usTimezones);
// [
//   { zoneName: 'America/New_York', abbreviation: 'EST', ... },
//   { zoneName: 'America/Chicago', abbreviation: 'CST', ... },
//   ...
// ]

// Get current time in a timezone
const currentTime = await getCurrentTime('America/New_York');
console.log(currentTime); // "2025-10-18T08:30:00.000Z"

// Convert time between timezones
const converted = await convertTime(
  '2025-10-18 14:00',
  'America/New_York',
  'Asia/Tokyo'
);
console.log(converted);
// {
//   originalTime: "2025-10-18T14:00:00.000Z",
//   fromTimezone: "America/New_York",
//   convertedTime: "2025-10-19T04:00:00.000Z",
//   toTimezone: "Asia/Tokyo",
//   timeDifference: 14
// }

Local package or live API?

This package ships a free, offline-capable snapshot of the data — that's still the right choice when the app must work offline, a periodic snapshot is enough, or you just need simple lookups.

The CountryStateCity API is worth adding alongside it when you need:

  • Freshness — data that updates without publishing a new package version.
  • Search — fuzzy, typo-tolerant, server-side search (csc.search.fuzzy(...)), not just exact-match local lookups.
  • Scale & support — configurable rate limits and support beyond a bundled snapshot.

Start free with 3,000 requests per month. Compare plans or get an API key.

npm install @countrystatecity/sdk
// Before
import { getTimezonesByCountry } from '@countrystatecity/timezones';

const tzs = await getTimezonesByCountry('US');
// After
import { createCSCClient } from '@countrystatecity/sdk';

const csc = createCSCClient({ apiKey: process.env.CSC_API_KEY! });
const { data: tzs } = await csc.timezones.byCountry('US');

See the full migration guide for error handling, retries, and more.

📖 API Reference

Core Functions

getTimezones()

Get all available timezones.

const timezones = await getTimezones();
// Returns: ITimezone[]

Bundle Impact: ~74KB

getTimezonesByCountry(countryCode: string)

Get timezones for a specific country.

const timezones = await getTimezonesByCountry('US');
// Returns: ITimezone[]

Parameters:

  • countryCode - ISO 3166-1 alpha-2 country code (e.g., 'US', 'IN')

Bundle Impact: ~0.3KB per country

getTimezoneInfo(timezoneName: string)

Get detailed information about a timezone including current time.

const info = await getTimezoneInfo('America/New_York');
// Returns: ITimezoneInfo | null

Returns:

{
  timezone: "America/New_York",
  currentTime: "2025-10-18T08:30:00.000Z",
  utcOffset: "UTC-05:00",
  isDST: false,
  gmtOffset: -18000
}

getTimezoneAbbreviations()

Get all timezone abbreviations (PST, EST, etc.).

const abbreviations = await getTimezoneAbbreviations();
// Returns: ITimezoneAbbreviation[]

Bundle Impact: ~5KB

getTimezonesByAbbreviation(abbreviation: string)

Find timezones by abbreviation.

const timezones = await getTimezonesByAbbreviation('EST');
// Returns: ITimezone[]

Utility Functions

convertTime(time, fromTimezone, toTimezone)

Convert time from one timezone to another.

const result = await convertTime(
  '2025-10-18 14:00',
  'America/New_York',
  'Europe/London'
);
// Returns: IConvertedTime

Parameters:

  • time - Time to convert (ISO string or Date object)
  • fromTimezone - Source timezone (IANA name)
  • toTimezone - Target timezone (IANA name)

getCurrentTime(timezoneName: string)

Get current time in a specific timezone.

const time = await getCurrentTime('Asia/Tokyo');
// Returns: string (ISO format)

isDaylightSaving(timezoneName: string, date?: Date)

Check if daylight saving time is active.

const isDST = await isDaylightSaving('America/New_York');
// Returns: boolean

Parameters:

  • timezoneName - IANA timezone name
  • date - Optional date to check (defaults to now)

getGMTOffset(timezoneName: string)

Get GMT/UTC offset in seconds.

const offset = await getGMTOffset('America/New_York');
// Returns: number (e.g., -18000 for UTC-05:00)

formatGMTOffset(offsetSeconds: number)

Format GMT offset from seconds to string.

const formatted = formatGMTOffset(-18000);
// Returns: "UTC-05:00"

isValidTimezone(timezoneName: string)

Validate if a timezone name is valid.

const isValid = await isValidTimezone('America/New_York');
// Returns: boolean

searchTimezones(searchTerm: string)

Search timezones by name (partial match).

const results = await searchTimezones('america');
// Returns: ITimezone[]

getUniqueAbbreviations()

Get all unique timezone abbreviations.

const abbreviations = await getUniqueAbbreviations();
// Returns: string[] (e.g., ['EST', 'PST', 'CST', ...])

getTimezonesByOffset(offsetSeconds: number)

Get timezones by GMT offset.

const timezones = await getTimezonesByOffset(-18000); // UTC-05:00
// Returns: ITimezone[]

🌍 Real-World Examples

Meeting Scheduler

import { convertTime, getTimezonesByCountry } from '@countrystatecity/timezones';

async function scheduleMeeting(localTime: string, attendeeCountries: string[]) {
  const meetingTimes = [];

  for (const countryCode of attendeeCountries) {
    const timezones = await getTimezonesByCountry(countryCode);
    const primaryTz = timezones[0];

    const converted = await convertTime(
      localTime,
      'America/New_York',
      primaryTz.zoneName
    );

    meetingTimes.push({
      country: countryCode,
      timezone: primaryTz.zoneName,
      time: converted.convertedTime
    });
  }

  return meetingTimes;
}

// Schedule 2 PM EST meeting for US, UK, and Japan
const times = await scheduleMeeting('2025-10-18 14:00', ['US', 'GB', 'JP']);

World Clock

import { getTimezonesByCountry, getCurrentTime } from '@countrystatecity/timezones';

async function createWorldClock(countryCodes: string[]) {
  const clocks = [];

  for (const code of countryCodes) {
    const timezones = await getTimezonesByCountry(code);
    for (const tz of timezones) {
      const currentTime = await getCurrentTime(tz.zoneName);
      clocks.push({
        location: tz.tzName,
        timezone: tz.zoneName,
        currentTime,
        offset: tz.gmtOffsetName
      });
    }
  }

  return clocks;
}

const worldClock = await createWorldClock(['US', 'GB', 'IN', 'AU', 'JP']);

DST Reminder

import { isDaylightSaving, getTimezonesByCountry } from '@countrystatecity/timezones';

async function checkDSTStatus(countryCode: string) {
  const timezones = await getTimezonesByCountry(countryCode);

  const dstStatus = [];
  for (const tz of timezones) {
    const isDST = await isDaylightSaving(tz.zoneName);
    dstStatus.push({
      timezone: tz.tzName,
      isDST,
      message: isDST
        ? 'Daylight Saving Time is active'
        : 'Standard Time'
    });
  }

  return dstStatus;
}

🔧 TypeScript Types

interface ITimezone {
  zoneName: string;        // "America/New_York"
  countryCode: string;     // "US"
  abbreviation: string;    // "EST"
  gmtOffset: number;       // -18000 (seconds)
  gmtOffsetName: string;   // "UTC-05:00"
  tzName: string;          // "Eastern Standard Time"
}

interface ITimezoneInfo {
  timezone: string;
  currentTime: string;     // ISO string
  utcOffset: string;       // "UTC-05:00"
  isDST: boolean;
  gmtOffset: number;
}

interface ITimezoneAbbreviation {
  abbreviation: string;    // "EST"
  name: string;            // "Eastern Standard Time"
  timezones: string[];     // ["America/New_York", ...]
}

interface IConvertedTime {
  originalTime: string;
  fromTimezone: string;
  convertedTime: string;
  toTimezone: string;
  timeDifference: number;  // hours
}

📊 Bundle Size

ActionBundle Size
Install package + import function~5KB
Load all timezones~74KB
Load timezones for one country~0.3KB
Load abbreviations~5KB
Typical usage~10KB

Data Coverage

  • 426 distinct IANA names across 432 country/zone records
  • 250 country codes, including 11 zone records for Antarctica (AQ)
  • 142 abbreviation mappings from upstream metadata

The snapshot contains zone names, offsets, abbreviations, and display names. It does not ship a historical transition database; date-specific conversions use the runtime's Intl timezone data.

Note: Timezone data is automatically sourced from the Countries States Cities Database and updates weekly.

🧪 Testing

# Run all tests
npm test

# Watch mode
npm run test:watch

All packages include comprehensive tests:

  • ✅ Unit tests
  • ✅ Integration tests
  • ✅ iOS/Safari compatibility tests

🔄 CI/CD & Automation

Continuous Integration

Every push and PR automatically:

  • ✅ Runs type checking with TypeScript
  • ✅ Executes comprehensive test suite
  • ✅ Builds the package
  • ✅ Validates bundle sizes
  • ✅ Tests iOS/Safari compatibility

Automated Data Updates

Weekly automated updates (Sundays at 00:00 UTC):

  • 📥 Downloads latest timezone data from authoritative sources
  • 🔄 Transforms into optimized structure
  • 🧪 Runs full test suite
  • 📝 Creates PR for review if changes detected

This ensures your application always has access to the most current timezone information without manual intervention.

Automated Publishing

Automated publishing to NPM on version changes:

  • 🔍 Detects version bumps in package.json
  • 📦 Builds and tests before publishing
  • 🚀 Publishes to NPM registry
  • 🏷️ Creates GitHub release with changelog

📄 License

ODbL-1.0 © dr5hn

This package and its data are licensed under the Open Database License (ODbL) v1.0. The data is sourced from the Countries States Cities Database which is also licensed under ODbL-1.0.

You are free to share, create, and adapt this database as long as you attribute the original sources, distribute adaptations under the same license, and don't use technical restrictions to lock down the data.

🤝 Contributing

Contributions are welcome! Please open an issue or PR.

For data-related issues (incorrect timezone data, missing timezones, wrong offsets, etc.), please report them to the Countries States Cities Database repository, which is the authoritative source of data for this package.

📦 Package Ecosystem

This package is part of the @countrystatecity package ecosystem:

  • @countrystatecity/countries — Server-side countries, states, and cities database. Environment: Node.js, Next.js API routes, Express. Bundle: <10KB initial load.

  • @countrystatecity/countries-browser — Browser-native version with jsDelivr CDN and lazy loading. Environment: React, Vue, Svelte, Vite, any browser. Same API as the server package — zero config, just import and use.

  • @countrystatecity/timezones (This package) — Comprehensive timezone data with conversion utilities. Environment: Server-side only. Bundle: <20KB initial load.

版本与发布记录

@countrystatecity/timezones 共发布 9 个版本,首次发布于 2025/10/18;过去 12 个月发布了 8 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.0.2latest2026/11/037 天前
2.0.12026/10/2912 天前
2.0.02026/10/1328 天前
1.0.92026/08/083 个月前
1.0.82026/08/083 个月前
1.0.72026/06/114 个月前

关于 @countrystatecity/timezones 的常见问题

@countrystatecity/timezones 是什么?

Comprehensive timezone data with conversion utilities and iOS/Safari support

如何安装 @countrystatecity/timezones?

在项目目录运行 npm install @countrystatecity/timezones,或使用 pnpm add / yarn add / bun add。

@countrystatecity/timezones 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@countrystatecity/timezones 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@countrystatecity/timezones 可以商用吗?

@countrystatecity/timezones 使用 ODbL-1.0 许可。声明的许可为 ODbL-1.0,请阅读许可原文确认使用条件。以上为概括,不构成法律意见,请以许可原文为准。

@countrystatecity/timezones 的下载量有多少?

根据 npm 官方下载统计,@countrystatecity/timezones 在 2026/10/11 – 2026/11/09 这 30 天内被下载 2,655 次,日均约 89 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@countrystatecity/timezones 还在维护吗?

最新版本 2.0.2 发布于 2026/11/03(7 天前);至今共发布 9 个版本,其中过去 12 个月发布了 8 个;首次发布于 2025/10/18。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。