LoginSignup
1
0

More than 1 year has passed since last update.

【JavaScript】期間重複をチェックする

Posted at

はじめに

開発する中で「期間Aと期間Bがあった場合、ABの期間が重複しているか判定する」処理が必要になり
初めて実装したのでまとめておきます。

実装例

sample.js

// 期間A:2022/07/01 - 2022/07/31 
const dateA = {
 start:  new Date('2022/07/01'),
 end: new Date('2022/07/31')
}

// 期間B:2022/07/31 - 2022/08/30
const dateB = {
 start:  new Date('2022/07/31'),
 end: new Date('2022/08/30')
}

上記のような期間Aと期間Bがあるとしたとき、ふたつの期間が重複しているか判定するには以下の条件式を使用します。

期間Aの開始時間 <= 期間Bの終了時間 && 期間Aの終了時間 >= 期間Bの開始時間

※比較演算子は、条件に応じて変更します。
期間が重複していればtrueが、重複していなければfalseが返ってきます。

上の例で当てはめてみると、

2022/07/01 <= 2022/08/30 && 2022/07/31 >= 2022/07/31

となり、右辺が成り立たない為trueが返ってきます。

参考サイト

1
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
1
0