Handle date and time with JavaScript moment.js


When dealing with date objects in JavaScript, moment.js is recommended.

It is much easier to handle than the JavaScript Date object, so it is easy to format date and validate the date calculation and character string format.

🐮 Installation

yarn add moment

🍮 How to use

Basic

import * as moment from 'moment';

moment().format();

Output in specified character string format

moment().format('MMMM Do YYYY, h:mm:ss a'); // May 11 2017, 8:36:01 Morning
moment().format('dddd'); // Thursday
moment().format(); // 2017-05-11T08:36:01+09:00

Calculate the relative date

moment('20111031', 'YYYYMMDD').fromNow(); // 6 years ago
moment().startOf('day').fromNow(); // 9 hours ago
moment().endOf('day').fromNow(); // 15 hours later

Please refer to the following link for details of date format that can be parsed.

Addition / Subtraction of Date

moment().subtract(10, 'days').calendar(); // 2017/05/01
moment().subtract(6, 'days').calendar(); // last Friday 08:36
moment().subtract(1, 'days').calendar(); // yesterday 08:36
moment().calendar(); // today 08:36
moment().add(1, 'days').calendar(); // tomorrow 08:36
moment().add(3, 'days').calendar(); // next Sunday 08:36
moment().add(10, 'days').calendar(); // 2017/05/21

Acquisition of year, month, day, hour, minute and second

var m = moment();

m.year(); // Year
m.month(); // Month (0〜11, so please be careful)
m.date(); // Day
m.day(); // The day of the week
m.hours(); // Hour
m.minutes(); // Minute
m.seconds(); // Second

Acquisition of days from 5/1 to today

moment().diff(moment([2017, 5, 1]), 'days'); //=> 10

Acquisition of the number of days of this month

moment().daysInMonth(); //=> 31

Show ISO8601

moment().format('YYYY-MM-DDTHH:mm:ss.SSSZ');
moment().toISOString();
new Date().toISOString();

🐡 References

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!