2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptにおける日付・時刻処理の設計:Dateオブジェクト、ISOフォーマット、ライブラリ運用の戦略

Posted at

概要

日付と時刻は**すべてのアプリケーションに現れる“状態”であり、“落とし穴”**でもある。
JavaScriptでは標準で Date オブジェクトが用意されているが、その操作性・可読性・正確性においては多くの課題がある。

本稿では、以下の観点から日付処理を設計する:

  • Dateオブジェクトの基礎と注意点
  • ISOフォーマットの活用
  • 時刻演算のトラップ
  • 日付ライブラリ(Luxon, date-fns等)の比較と戦略
  • 現実的な日付処理のベストプラクティス

1. Date オブジェクトの基礎

const now = new Date();
console.log(now.toISOString()); // ISO 8601形式
  • ✅ コンストラクタにISO文字列を渡せば、UTCとして正確に解釈される
  • Date.parse()"YYYY-MM-DD" など曖昧な形式は避ける
new Date('2024-12-01') // ❌ 環境依存(UTCかローカルか曖昧)
new Date('2024-12-01T00:00:00Z') // ✅ 明示的にUTC

2. ISO 8601形式を使う理由

const date = new Date('2024-12-01T15:00:00Z');
  • ✅ 一意性がある
  • ✅ タイムゾーンを含めて伝達可能
  • ✅ バックエンド・DB・API連携との親和性が高い

3. 日付の演算と注意点

❌ 手動で加算・減算しようとする

const d = new Date();
d.setDate(d.getDate() + 1); // ✅ ただし月末→翌月などに注意

→ ✅ Dateは内部的にUNIXタイム(ミリ秒)で保持されているため、演算は慎重に行う


4. 時刻の比較と差分

const a = new Date('2024-01-01T00:00:00Z');
const b = new Date('2024-01-02T00:00:00Z');

const diffMs = b - a; // ✅ 数値比較が可能
const diffDays = diffMs / (1000 * 60 * 60 * 24); // → 1

5. 日付の整形:toLocaleString() vs 外部ライブラリ

❌ 標準の toLocaleString() は非一貫

new Date().toLocaleDateString('ja-JP'); // "2025/3/30"

→ ✅ 表示形式が環境依存で一貫性がない


6. 推奨されるライブラリと設計思想

✅ Luxon(Moment.jsの後継)

import { DateTime } from 'luxon';

const now = DateTime.now().setZone('Asia/Tokyo');
const iso = now.toISO(); // ISO文字列
const formatted = now.toFormat('yyyy-MM-dd HH:mm');
  • ✅ タイムゾーンを意識した設計が可能
  • ✅ 明示的な構文と操作性

✅ date-fns(関数型ライブラリ)

import { format, parseISO, addDays } from 'date-fns';

const date = parseISO('2024-01-01T00:00:00Z');
const next = addDays(date, 1);
const output = format(next, 'yyyy-MM-dd');
  • ✅ 関数中心の柔軟設計
  • ✅ tree-shakingに優れ、軽量
  • ❌ タイムゾーン処理は別パッケージに依存

7. よくある失敗と防止策

❌ 文字列フォーマットが環境でブレる

→ ✅ 表示用の整形は toFormat() / format() で明示的に


❌ 日時をローカル/UTCで混同

new Date('2025-01-01'); // ❌ ローカル解釈

→ ✅ "2025-01-01T00:00:00Z" のようにUTC明記する


❌ 日時操作を標準のDateで手動実装

→ ✅ 日付ライブラリで明示的に設計されたAPIを使うべき


設計判断フロー

① 単純な日時取得? → Date.now() / new Date()

② 表示用途? → Luxon.format() / date-fns.format()

③ 差分・加減算? → addDays, diffDaysなどのライブラリ使用

④ タイムゾーンを扱う? → Luxon推奨

⑤ データ保存・API通信? → ISO 8601 で統一

結語

日付と時刻は、アプリケーションの中でもっとも誤解されやすく壊れやすいデータである。

  • Dateは曖昧に動く。
  • ISOで固定し、ライブラリで制御せよ。
  • フォーマットも比較も演算も、意図を明示せよ。

「その日付は“いつの、誰の、どの瞬間”か?」――
それに答えられる構造が、正しく設計された時刻表現である。

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?