ひびのログ

日々ではないけどログを出力していくブログ

その date-fns-tz、本当に必要?

実は date-fns で事足りるというケースが多いよ、という話。

date-fns-tz はどういうライブラリ?

date-fns-tz の README より引用。

Working with UTC or ISO date strings is easy, and so is working with JS dates when all times are displayed in a user's local time in the browser. The difficulty comes when working with another time zone's local time, one other than the current system's, like on a Node server or when showing the time of an event in a specific time zone, like an event in LA at 8pm PST regardless of where a user resides. 略 Since date-fns always returns a plain JS Date, which implicitly has the current system's time zone, helper functions are provided for handling common time zone related use cases. https://github.com/marnusw/date-fns-tz?tab=readme-ov-file#overview

要約すると、以下のようなことが書かれている。

  • 実行環境と同じタイムゾーンで表示するときは簡単だけど違うタイムゾーンで表示するときは難しいよね
  • date-fns はプレーンな Date オブジェクトを使っていて、ユーザーのタイムゾーンを暗黙的に持っている(前提としている)よ

これに対して date-fns-tz は、ユーザーがいるところと違うタイムゾーンで表示したいときに使うライブラリである。

タイムゾーンが含まれている文字列のパースには必要では?

date-fns の parseISO で考慮されているので不要(date-fns でパースできる)。

実際に試しても、date-fns と date-fns-tz で全く同じ出力が得られる。

date-fns と date-fns-tz でタイムゾーン(Z)が含まれているコードをパースしたコード。同じ出力が得られている。

date-fns の該当のコードはここparseTimezone でパースして offset を得ている。 return しているところ で計算しつつ Date オブジェクトを生成している。

結論

実行環境と同じタイムゾーンを使うなら date-fns-tz は不要で、date-fns で事足りる。 もし違うタイムゾーンを使いたいなら、date-fns-tz が必要。

関連