iTranslated by AI
Building a Lightweight Timezone Converter with Intl API (Astro/TypeScript)
Introduction
"I want to convert UTC to JST (Japan Standard Time)" or "I want to check logs in local time"—these are everyday needs for engineers working on global projects.
However, handling time zones is surprisingly complex. Introducing external libraries like Moment.js or date-fns can increase the bundle size by dozens or even hundreds of KB.
DevToolKits implements highly functional time zone conversion using only the browser's native Intl API, without relying on any external libraries.
In this article, I will explain the "zero-dependency" implementation technique.
Implementation Highlights
1. Formatting with Intl.DateTimeFormat
You can format dates according to a specified time zone using the browser's standard Intl.DateTimeFormat.
const d = new Date();
const timeZone = 'Asia/Tokyo';
const parts = new Intl.DateTimeFormat('en-CA', {
timeZone,
hour12: false,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
})
.formatToParts(d)
.reduce((acc, cur) => ({ ...acc, [cur.type]: cur.value }), {} as any);
// Can be reformatted to ISO format, etc., using parts.year, parts.month, etc.
By using formatToParts, you can retrieve each element such as year, month, and day individually, allowing for flexible reformatting.
2. Getting the Time Zone Offset (e.g., GMT+09:00)
To find out how many hours a specific time zone is offset from UTC, the timeZoneName: 'shortOffset' option is convenient.
const offsetName = new Intl.DateTimeFormat('en-US', {
timeZone,
timeZoneName: 'shortOffset',
hour: '2-digit',
}).formatToParts(d)
.find((p) => p.type === 'timeZoneName')?.value;
// Obtains strings like "GMT+9" or "GMT-8"
By normalizing the obtained offset string, we generate standard time zone-included formats such as 2024-01-01T00:00:00+09:00.
3. Commitment to Lightweight Design
The greatest strength of this tool is that it has "zero dependencies."
By making full use of native browser features, we have achieved:
- Ultra-fast loading: No need to download additional JS.
- Up-to-date time zone data: It reflects the latest IANA time zone data held by the operating system or browser.
Summary
While time zone conversion tools used to require heavyweight libraries, they can now be implemented just as powerfully using only the Intl API.
Simple and efficient implementation is the key to creating tools that are most useful for developers.
DevToolKits also provides many other useful tools for engineers.
Discussion