LoginSignup
1
3

More than 1 year has passed since last update.

Lambdaで、現在日時と特定の日付を容易に比較する (Node.js)

Last updated at Posted at 2022-05-05

はじめに

Lambdaで、現在時刻と、特定の期間を比較して、範囲内かどうか短いコードで判定する方法をまとめました。
面倒なので、ライブラリも使用しない方法になります。

現在日時が特定の期間内かどうか判定

解説

  • getTime()は常にUTCでの値の取得になるため、現在日時もUTCで取得します。

  • content.fromcontent.toに特定の日付を入れてください。
    (必ず"xxxx-xx-xxTxx:xx+09:00"の形式になるようにしてください。)

  • UTCでの比較にはなりますが、content内の"xxxx-xx-xxTxx:xx+09:00"は、JSTにしております。

つまり、現在時刻はUTCcontent内は、JSTからgetTime()によってUTCに変換され、UTC同士で比較されることになります。

下記の場合ですと、
日本時間で、2022/5/5の12時2022/5/8の12時までの範囲に現在日時が入っているかどうか判定します。

コード内容

const content = {
  // 日本時間で記載すること
  from: "2022-05-05T12:00+09:00",
  to: "2022-05-08T12:00+09:00",
};

const now = Date.now();
const from = new Date(content.from).getTime();
const to = new Date(content.to).getTime();

exports.handler = (event, context, callback) => {
  
  if ( from <= now && now <= to) {
    console.log("within the period");
    return;
  }
  console.log("out of term");
};

パフォーマンス

現在時刻を取得するだけであれば、new Date().getTime()よりもDate.now()の方がパフォーマンスがよいようです。

参考

日付の差分を取得する場合こちらの方法がよいです。

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