LoginSignup
13
13

More than 5 years have passed since last update.

Moment.js(moment-range)で日付が範囲内であるか調べる

Last updated at Posted at 2016-02-02

Moment.js は、日付時刻の操作を行なったり整形したりがとても楽になるJavaScriptライブラリです。:smile::thumbsup:

今回はMoment.jsの拡張ライブラリである、moment-range を使って、日付が範囲内であるかを調べたいと思います。 :triumph: :punch:

:sparkles: moment-range :sparkles:

moment-range を使うことで、日付が範囲内であるかを調べることが出来ます。

インストール :arrow_down:

npm、bowerでインストールすることが出来ます。Moment.jsと一緒にインストールしてください。

npmの場合
npm install moment
npm install moment-range
bowerの場合
bower install moment 
bower install moment-range

使い方 :sun_with_face: :full_moon_with_face: :new_moon_with_face:

日付が範囲内であるかどうかは、moment-rangeのrange(範囲指定)contains(調べる対象)で調べることが出来ます。

例えば…今日2016年2月3日(:scream: 節分 :japanese_ogre:)は、

  • A.2015年12月1日から2016年3月1日の間かどうか
  • B.2016年3月1日から2016年4月1日の間かどうか

を調べたいとします。

日付が範囲内であるかを調べるソース
var moment = require("moment");
require("moment-range");

// 2016年の節分の日をセット(以下のどれかで)
// 今日が2016年2月3日だったらこれでOK
// var setsubunDate = moment();

// Dateオブジェクト(第二引数は0が1月になります)
// var setsubunDate = moment(new Date(2016, 1, 3)); 

// Arrayはすっきりして便利
var setsubunDate = moment([2016, 1, 3]);

// A rangeで範囲を指定
var rangeA = moment.range(new Date(2015, 11, 1), new Date(2016, 2, 1));

// B rangeで範囲を指定
var rangeB = moment.range(new Date(2016, 2, 1), new Date(2016, 3, 1));

// A containsで日付が範囲内かどうかを調べる
console.log(rangeA.contains(setsubunDate)); // True
console.log(rangeA.contains(setsubunDate.toDate())); // これもTrue (moment.toDate()でDate型取得)

// B containsで日付が範囲内かどうか調べる
console.log(rangeB.contains(setsubunDate)); // False
console.log(rangeB.contains(setsubunDate.toDate())); // これもFalse (moment.toDate()でDate型取得)


今日2016年2月3日(:scream: 節分 :japanese_ogre:)は、

  • A.2015年12月1日から2016年3月1日の間である=True
  • B.2016年3月1日から2016年4月1日の間ではない=False

ということが分かりました。

簡単でしょ!:smile::clap:

moment-range を使うことで簡単に日付が範囲内であるかを調べることが出来ました。moment-rangeには他にもいろんな機能がありそうなので是非挑戦してみてくださ〜い(僕も挑戦します!)

参考

13
13
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
13
13