const d1 = new Date('2020-01-01') // Jan 1, midnight UTCtzjs.getOffset('Europe/Berlin', d1) // -60const d2 = new Date('2020-06-01') // June 1, now we're on daylight savingstzjs.getOffset('Europe/Berlin', d2) // -120tzjs.getOffset('America/Los_Angeles', new Date()) // current offset in LA/SF// Returns 420 or 480, depending on whether we're on daylight savingsconst o1 = {hour: 'numeric', minute: '2-digit', timeZoneName: 'short'}tzjs.fmt(o1).format(d1)// example: "4:00 PM PST". localizes to the user's timezone and language
support all the world's timezones, including DST and historical changes, in under 1KB of javascript!
getOffset is a few lines of very tricky code, working around a limitation in window.Intl.
fmt is a thin wrapper around Intl.DateTimeFormat. it's shorter to type and memoized, which we've measured to be important for performance.
comparison
the two most popular libraries for dealing with dates in the browser are moment and date-fns.
if you needed to format times in a specific timezone--any timezone other than browser local or UTC--the situation was grim. until now!
const options = { hour: '2-digit', timeZoneName: 'short', timeZone: 'Europe/Berlin'}const format = window.Intl.DateTimeFormat('en-US', options)format.format(new Date('2020-01-01')) // Midnight Jan 1 UTC// "1 AM GMT+1"format.format(new Date('2020-06-01')) // Midnight June 1 UTC// "2 AM GMT+2" (because of DST)
so under the hood, browser must already have the timezone database, and must already be calculating offsets. however, the offsets are not exposed in the API.
then how does tzjs work?
we work around this omission via a cute hack. we use window.Intl to format a given instant in both UTC and the target timezone. then, we parse both formatted times and subtract. turns out you can do this in just a few lines of code. see index.js.
is it fast?
reasonbly. all that string parsing is slower than moment but fast enough that it would be 0% of your render time in most UIs.
on my 2011-era Thinkpad x220:
$ npm run benchComputing offsets for 744 dates x 493 zonestzjs.getOffset: 366792 offsets in 5946msmomentTz.utcOffset: 366792 offsets in 386ms
that works out to 16us per offset for tzjs vs 1us for moment-timezone
tzjs saves you ~400KB from your minified bundle size, which can cut page load time significantly.
date formatting
so the built-in Intl.DateTimeFormat is lots lighter than moment. however, writing DateTimeFormats everywhere can get cumbersome.
not only that, it can be slow. we've seen the DateTimeFormat constructor show up in profiles, taking up more than half of our frontend CPU!
solution: tzjs.fmt
we've found the following to work well. specifically, it's fast and light.
create a file that can be shared across your frontend. ours is called date.js: