JSTZ - Timezone Detection

2.1.1 · maintenance · verified Sun Apr 19

JSTZ is a JavaScript library designed for client-side timezone detection within a user's browser, returning an IANA zone info key (e.g., 'America/Los_Angeles'). It is currently at version 2.1.1. As an unofficial fork of the original `pellepim/jstimezonedetect` project, its primary differentiator is enabling installation and usage via NPM for module-based environments (like Webpack or Browserify), as the original focused on CDN distribution. While there isn't a strict, frequent release cadence, updates have addressed specific bugs and improved TypeScript definitions. It's often used in conjunction with server-side frameworks or other date-time parsing libraries like Moment Timezone to determine the user's local timezone without requiring user input.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to import jstz, detect the user's timezone, and display its IANA name. It includes error handling and notes for both browser and Node-like environments.

import jstz from 'jstz';

function detectAndDisplayTimezone() {
  try {
    const timezone = jstz.determine();
    const name = timezone.name();
    console.log(`Detected timezone: ${name}`);

    // Example of using the timezone name (e.g., sending to a server)
    // fetch('/api/user/timezone', {
    //   method: 'POST',
    //   headers: { 'Content-Type': 'application/json' },
    //   body: JSON.stringify({ timezone: name })
    // });

    document.getElementById('timezone-output').innerText = `Your detected timezone is: ${name}`;
  } catch (error) {
    console.error('Failed to detect timezone:', error);
    document.getElementById('timezone-output').innerText = 'Failed to detect timezone.';
  }
}

// Run detection on page load in a browser environment
if (typeof window !== 'undefined') {
  window.addEventListener('load', detectAndDisplayTimezone);
  // For quick testing in a Node-like environment without a DOM
  if (!document.getElementById('timezone-output')) {
    console.log('Running jstz.determine() in a non-DOM context...');
    const timezone = jstz.determine();
    console.log(`Node-like detected timezone: ${timezone.name()}`);
  }
}

view raw JSON →