1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【TypeScript】date-fns が便利すぎたのでよく使う関数まとめ

Posted at

はじめに

こんにちは。アメリカ在住で独学エンジニアを目指している Taira です。

TypeScript で日付を扱うとき、Date オブジェクトを素で操作するとかなり面倒ですよね。
たとえばフォーマットひとつとっても、

const d = new Date()
console.log(`${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`)

みたいに書かないといけない。

そんな煩わしさを解消してくれるのが、
軽量で関数型スタイルな日付ライブラリ date-fns です。


インストール

私はReact V19 + Viteの環境で使っていますが、最初からdate-fnsは入っているので特に追加インストールは不要です。


よく使う関数まとめ

ここからは、日常的によく使う関数を中心に紹介していきます。


🕐 format:日付をフォーマットする

Date オブジェクトを任意の形式で文字列に整形できます。

import { format } from "date-fns"
import { ja } from "date-fns/locale"

const now = new Date()

console.log(format(now, "yyyy-MM-dd"))
// => 2025-10-07

console.log(format(now, "yyyy年MM月dd日 (E)", { locale: ja }))
// => 2025年10月07日 (火)

📘 よく使う書式トークン一覧

トークン 意味
yyyy 年(4桁) 2025
MM 月(2桁) 10
dd 日(2桁) 07
E 曜日
HH:mm:ss 時間 13:45:10
yyyy-MM-dd'T'HH:mm:ss'Z' タイムゾーン 2025-10-07T12:00:00Z

🔖 parseISO:ISO文字列からDate型に変換

APIから受け取る "2025-10-07T12:00:00Z" のような文字列を
Date オブジェクトに変換します。

import { parseISO } from "date-fns"

const date = parseISO("2025-10-07T12:00:00Z")
console.log(date)
// => Tue Oct 07 2025 21:00:00 GMT+0900 (日本標準時)

ISO形式はAPI通信でよく使われるので、
これを知らないと時差バグに悩まされがちです。


addDays / addMonths / addYears:日付を加算

未来や過去の日付を簡単に算出できます。
Date オブジェクトは不変なので、新しい Date が返ってきます。

import { addDays, addMonths, addYears } from "date-fns"

const today = new Date()

console.log(addDays(today, 7))   // 7日後
console.log(addMonths(today, 1)) // 1ヶ月後
console.log(addYears(today, -1)) // 1年前

ネーミングも直感的で覚えやすいのが嬉しいポイント。


🔁 differenceInDays:2つの日付の差分を求める

指定した2つの日付の「日数差」を取得できます。
スケジュール管理や期限チェックでよく使われる関数です。

import { differenceInDays } from "date-fns"

const start = new Date("2025-10-01")
const end = new Date("2025-10-07")

console.log(differenceInDays(end, start))
// => 6

differenceInHoursdifferenceInMinutes などの派生関数も豊富です。


🌅 startOfDay / endOfDay:1日の始まり・終わりを取得

「今日中に有効」など、日付範囲の比較で使う定番関数です。

import { startOfDay, endOfDay } from "date-fns"

const today = new Date()

console.log(startOfDay(today)) // => 2025-10-07T00:00:00.000Z
console.log(endOfDay(today))   // => 2025-10-07T23:59:59.999Z

たとえば「期限が今日まで」を判定したい場合は
expireDate <= endOfDay(today) のように書けます。
あとは、startOfDay などを使用しないで日付比較をすると、秒単位でズレることがあります。
なので、日付の比較をする際は、startOfDay や endOfDay を使うのが無難です。


🕰️ isBefore / isAfter:日付の前後関係を比較

import { isBefore, isAfter } from "date-fns"

const a = new Date("2025-10-01")
const b = new Date("2025-10-07")

console.log(isBefore(a, b)) // true
console.log(isAfter(b, a))  // true

単純な <> でも書けますが、
可読性を高めるならこういった関数を使うのがベターです。


🗓 eachDayOfInterval:日付の配列を生成

指定期間の全日を配列で取得できます。
カレンダーUIなどで重宝します。

import { eachDayOfInterval, format } from "date-fns"

const days = eachDayOfInterval({
  start: new Date("2025-10-01"),
  end: new Date("2025-10-07"),
})

console.log(days.map(d => format(d, "MM/dd")))
// => ["10/01", "10/02", "10/03", "10/04", "10/05", "10/06", "10/07"]

まとめ

✅ date-fns の魅力

  • 必要な関数だけ個別 import(軽量!)
  • TypeScript対応済み
  • ロケール対応完備
  • date-fns-tz でタイムゾーン操作も可能
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?