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?

Dateオブジェクトとdate-fns

Posted at

Date オブジェクトとは

JavaScript で日付や時刻を扱う際に必須となるのが Date オブジェクト

1. 基本構文

const date = new Date();

引数なしで呼び出すと、現在の日時 を表す Date オブジェクトが生成。
生成されるのはオブジェクトであり、数値や文字列ではない。

const now = new Date();
console.log(now); 
// 例: Sun Sep 07 2025 14:35:12 GMT+0900 (Japan Standard Time)

2. 引数の指定方法

new Date() は 引数の与え方によって挙動が変わります。

2.1 日付文字列を渡す

const d1 = new Date("2025-09-07");
console.log(d1); 
// Sun Sep 07 2025 09:00:00 GMT+0900 (JST)

2.2 年・月・日などを個別に指定

const d2 = new Date(2025, 8, 7); // 月は 0 始まり → 8 は 9月
console.log(d2); 
// Sun Sep 07 2025 00:00:00 GMT+0900 (JST)

2.3 ミリ秒を渡す

const d3 = new Date(0); 
console.log(d3); 
// Thu Jan 01 1970 09:00:00 GMT+0900 (JST)

※ここでの 0 は UNIX エポック(1970/1/1 00:00:00 UTC)を基準とするミリ秒。

date-fnsとは

date-fnsは、JavaScriptやTypescript上で日付や時間を簡単に操作できる軽量なライブラリ。
date-fnsを入れていたら、基本はdate-fnsを使用するべき。

1. フォーマット

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

const now = new Date();
console.log(format(now, "yyyy/MM/dd HH:mm:ss")); 
// 2025/09/07 15:10:00

console.log(format(now, "PPP", { locale: ja })); 
// 2025年9月7日

2. 日付の加算・減算

import { addDays, subMonths } from "date-fns";

const today = new Date();
const nextWeek = addDays(today, 7);
const lastMonth = subMonths(today, 1);

console.log(nextWeek);   // 今日から7日後
console.log(lastMonth);  // 今日から1か月前

3. 差分の計算

import { differenceInDays } from "date-fns";

const d1 = new Date(2025, 8, 7);
const d2 = new Date(2025, 8, 1);

console.log(differenceInDays(d1, d2)); 
// 6

4. 日付の比較

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

const d1 = new Date(2025, 8, 7);
const d2 = new Date(2025, 8, 10);

console.log(isBefore(d1, d2)); // true
console.log(isAfter(d1, d2));  // false
console.log(isEqual(d1, d1));  // true
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?