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?

目次

はじめに

  const today = new Date();
  
  const startDate = "2026-06-24 00:00:00";
  const endDate = "2026-06-25 18:00:00";
  
  console.log(today);
  // Thu Jun 25 2026 16:18:18 GMT+0900 (日本標準時)
  
  console.log(today.toDateString() >= startDate);
  // true
  
  console.log(today.toDateString() <= endDate);
  // false ← trueになるべき

現在が「2026年6月25日の16時18分」なのに、
endDate(2026年6月25日18時00分)よりも小さい日時(古い日時)ではない = 新しい日時である、という結果になっています。

原因

日付比較ではなく、文字列同士での比較になっているからです。

today.toDateString() <= endDate

"Thu Jun 25 2026" <= "2026-06-25 18:00:00"

と比較していることになります。

これだと辞書順(文字コード順)で比較されてしまい、正確な比較を行えません。

解決方法

Dateオブジェクト同士で比較します。

const today = new Date();

const startDate = new Date("2026-06-24T00:00:00");
const endDate = new Date("2026-06-25T18:00:00");

const showQuestionnaire =
    today >= startDate &&
    today <= endDate;

もしくは数値にする場合はこちらです。


const showQuestionnaire =
  today.getTime() >= startDate.getTime() &&
  today.getTime() <= endDate.getTime();

補足

(1)Tについて

修正前:2026-06-24 00:00:00
 ↓
修正後:2026-06-24T00:00:00

修正後には「T」が入っていることが分かります。

Tは日付と時刻の区切り文字になります。

T はリテラル文字で、文字列の時刻部分の始まりを示します。
T は時刻部分を指定する場合は必須です。

Date - JavaScript | MDN より

YYYY-MM-DDThh:mm:ss

これは「ISO 8601形式」と呼ばれ、JavaScriptが標準的に解釈できる日付文字列です。

(2)時刻について

それから、today.toDateString()を使うと時刻が消えます。

console.log(new Date("2026-06-25T16:14:13").toDateString())
// Thu Jun 25 2026

console.log(new Date("2026-06-25T16:14:13"))
// Thu Jun 25 2026 16:14:13 GMT+0900 (日本標準時)

そのため時刻を含めて大小を比較したい場合はDateオブジェクトを使用します。

参考サイト

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?