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?

More than 1 year has passed since last update.

【JS】日付の比較 (端末のタイムゾーンに関わらず常にJSTで!)

Last updated at Posted at 2023-10-10

「現在日付の2日後より前かどうか調べる関数」を作成します。

要件:
・OSのタイムゾーンに関わらずJSTで計算されるようにしたい!

⇒UTCの時刻を取得して+9することで、どこの国の時間で実行しても常にJSTで計算されるようになります。

//現在日付の2日後より前かどうか調べる関数
const isDateWithinTwoDays = (date) => {
    //現在日付の取得
    var now = new Date() 
    
    // 現在日付から2日後
    const twoDaysLater = new Date(
        now.getUTCFullYear(),
        now.getUTCMonth(),
        now.getUTCDate() + 2,
        now.getUTCHours() + 9
    )
    
    const inputDate = new Date(date)
    
    const numTwoDaysLater =
        twoDaysLater.getFullYear() * 10000 + twoDaysLater.getMonth() * 100 + twoDaysLater.getDate()
        
    const numInputDate = inputDate.getFullYear() * 10000 + inputDate.getMonth() * 100 + inputDate.getDate()
    
    if (numInputDate < numTwoDaysLater) {
        return true
    } else {
        return false
    }
}

上記のようにすることで、例えば、2023年12月31日2024年1月1日の比較が
2023123120240101のような数値に置き換えられて比較されます。

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?