LoginSignup
50
47

More than 5 years have passed since last update.

moment.js の使い方

Last updated at Posted at 2014-11-13

moment.js で日付け計算をしてみます。

説明

javascriptの標準機能では補えない機能を簡単に使えるライブラリです。
例題を交えて使い方を説明します。

使い方

今日が2014年11月12日(水曜日)という前提で、

:one: 今日を算出
moment();
[ result ] Wed Nov 12 2014 23:30:03 GMT+0900 (東京 (標準時))

:two: 日付けをフォーマットする
moment().format('YYYY月MM年DD日');
[ result ] 2014月11年12日

:three: 今日は何曜日?
moment.lang('ja', {weekdays: ["日","月","火","水","木","金","土"]});
moment().format('dddd曜日');

[ result ] 水曜日

:four: 今週の月曜日の日付けは?
moment().day(1).format('YYYY月MM年DD日 dddd曜日');
[ result ] 2014月11年10日月曜日

// moment().day(1);は今週の月曜を指します。
// 日:0, 月:1, 火:2, 水:3, 木:4, 金:5, 土:6

:five: 今月の末日は?
// 日数だけなら moment().daysInMonth(); // 30
moment().endOf("month").format('YYYY月MM年DD日 dddd曜日');
[ result ] 2014月11年30日 日曜日

:six: 3年前の今日は?
moment().subtract(3, 'years').format('YYYY月MM年DD日 dddd曜日');
[ result ] 2011月11年12日 土曜日

// 2日前は、moment().subtract(2, 'days');
// 2月前は、moment().subtract(2, 'months');

:seven: 3年後の今日は?
lmoment().add(3, 'years').format('YYYY月MM年DD日 dddd曜日');
[ result ] 2017月11年12日 日曜日

// 2日後は、moment().add(2, 'days');
// 2月後は、moment().add(2, 'months');

:eight: A (2011/9/1) は、B (2015/3/1) より前か?
var dateA = moment([2011, 9, 1]);
var dateB = moment([2015, 3, 1]);
dateA.isBefore(dateB);

[ result ] true

:nine: A (2011/9/1) は、B (2015/3/1) より後か?
var dateA = moment([2011, 9, 1]);
var dateB = moment([2015, 3, 1]);
dateA.isAfter(dateB);

[ result ] false

:ten: A (2011/9/1) から、B (2015/3/1) までは何年間?
var dateA = moment([2011, 9, 1]);
var dateB = moment([2015, 3, 1]);
dateA.diff(dateB, 'years');

[ result ] -3

// 〇日間は、dateA.diff(dateB, 'days');
// 〇月間は、dateA.diff(dateB, 'months');

50
47
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
50
47