0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

DST・タイムゾーンを正しく扱うカウントダウントラッカーを作った

0
Posted at

作ったもの

Countdown Dayshttps://sen.ltd/portfolio/countdown-days/

スクリーンショット

  • 複数イベントの同時追跡
  • 未来は「あと○日」、過去は「○日前」
  • ライブ h/m/s 更新
  • 10 プリセット(日本の祝日、誕生日、試験、結婚式 など)
  • URL で共有可能
  • localStorage 永続化

vanilla JS、ゼロ依存、ビルド不要node --test で 42 ケース。

DST に強い日数計算

const fromUTC = Date.UTC(from.getFullYear(), from.getMonth(), from.getDate());
const toUTC = Date.UTC(to.getFullYear(), to.getMonth(), to.getDate());
return Math.round((toUTC - fromUTC) / (1000 * 60 * 60 * 24));

Date.UTC(...)ローカル TZ を無視して UTC 午前 0 時のタイムスタンプを返す。UTC 午前 0 時同士の差は必ず 86400000ms の整数倍 = 正確なカレンダー日数。

ナイーブな (to - from) / 86400000 だと DST の切替日に 0.04 日のズレが出る。丸めで運良く救われる場合もあるが、時刻が午前 0 時以外だと失敗する。

秒を揃えるライブ更新

function tick() {
  update();
  const msUntilNext = 1000 - (Date.now() % 1000);
  setTimeout(tick, msUntilNext);
}

setInterval(1000) だと毎回少しずつオフセットがずれて表示が引っかかる。次の秒境界に揃えて呼び出せば綺麗に刻む。

isPast 判定は < 0

const isPast = diff < 0;

<= 0 ではない。ちょうど 0 は「今」であって過去ではない。イベント到達の瞬間だけ 0 を表示し、次のティックで反転する。

シリーズ

100+ 公開ポートフォリオ シリーズの #93 です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?