Dev.to WebDev 🛠 Dev 👁 0 📖 2 min read

Why Your New Year Countdown Is Wrong in Other Time Zones (and the JavaScript Fix)

Every December, a lot of countdown pages quietly show the wrong number. The cause is almost always the same: the code counts down to midnight in the developer's own time zone, not the visitor's. Here is the bug and a sm

Every December, a lot of countdown pages quietly show the wrong number. The cause is almost always the same: the code counts down to midnight in the developer's own time zone, not the visitor's.

Here is the bug and a small fix.

The common mistake

const target = new Date('2027-01-01T00:00:00');
const ms = target - new Date();

A string without a time zone is parsed as local time, so this looks right on your machine. But if you want one shared moment for everyone (for example midnight UTC), a visitor in another country sees a different result than you expect. The reverse mistake is also common: hard-coding UTC when users expect their own midnight.

Pick the meaning first

Decide which one you want:

  1. Local midnight: each visitor counts down to midnight where they are. Build the date from the visitor's current year with new Date(year + 1, 0, 1).
  2. One global moment: use an explicit UTC string, such as 2027-01-01T00:00:00Z.
function msToNewYear(now = new Date()) {
  const next = new Date(now.getFullYear() + 1, 0, 1, 0, 0, 0); // local midnight
  return next - now;
}

Building the target from now.getFullYear() + 1 also means the code keeps working after 1 January without a manual edit.

Format the remaining time

function parts(ms) {
  const s = Math.max(0, Math.floor(ms / 1000));
  return {
    days: Math.floor(s / 86400),
    hours: Math.floor((s % 86400) / 3600),
    minutes: Math.floor((s % 3600) / 60),
    seconds: s % 60,
  };
}

Avoid drift

Do not add one second per setInterval tick, because timers drift when a tab is in the background. Recompute from the clock on every tick:

setInterval(() => render(parts(msToNewYear())), 250);

Edge cases worth testing

  • Daylight saving changes: the local-midnight method handles them, because the Date constructor does the calendar maths.
  • A device clock set wrong: show the difference, but do not trust it for anything important.
  • Visitors in different hemispheres: everyone counts to the same calendar date, but at different real moments, which is what most people expect.

Want to see a working version?

I keep a free in-browser New Year countdown at https://alarmsclock.live/new-year-countdown/ that follows the local-midnight approach above. It needs no sign-up and runs entirely in the page.

If you have hit another time zone bug in a countdown, tell me in the comments.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.