Building a World Clock with Automatic DST — The Timezone Pitfalls
Timezone handling is where confident developers become humbled developers. Here's what I learned building a 33-city world clock.
The Wrong Way
// DON'T do this
function getTimeInNewYork(date) {
const offset = -5; // EST
return new Date(date.getTime() + offset * 60 * 60 * 1000);
}
This breaks during Daylight Saving Time. New York is UTC-4 in summer, UTC-5 in winter.
The Right Way: Intl.DateTimeFormat
function getTimeInZone(timezone) {
return new Intl.DateTimeFormat('en-US', {
timeZone: timezone,
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
}).format(new Date());
}
getTimeInZone('America/New_York'); // Automatically handles DST
Intl.DateTimeFormat uses the IANA timezone database, which includes all historical and current DST rules.
Getting UTC Offset
function getUtcOffset(timezone) {
const date = new Date();
const utcDate = new Date(date.toLocaleString('en-US', { timeZone: 'UTC' }));
const tzDate = new Date(date.toLocaleString('en-US', { timeZone: timezone }));
const diff = (tzDate - utcDate) / (1000 * 60 * 60);
return diff; // e.g., 9 for Seoul, -4 or -5 for New York
}
Is It Day or Night?
function isDaytime(timezone) {
const hour = parseInt(
new Intl.DateTimeFormat('en-US', {
timeZone: timezone,
hour: 'numeric',
hour12: false,
}).format(new Date())
);
return hour >= 6 && hour < 20;
}
Real-Time Updates
Use setInterval to update all clocks, but be careful about performance:
function startClock(timezones, onTick) {
const tick = () => {
const now = new Date();
const times = timezones.map(tz => ({
timezone: tz,
time: getTimeInZone(tz),
offset: getUtcOffset(tz),
isDay: isDaytime(tz),
}));
onTick(times);
};
tick(); // Immediate first render
return setInterval(tick, 1000);
}
The 33 Cities
I chose cities to cover all major business hubs across every region. The key insight: use IANA names, not abbreviations. America/New_York works forever; EST is ambiguous and breaks.
Live at toolzip.app/tools/world-clock — 33 cities, DST-aware, real-time.
Top comments (0)