It is also hard to add and subtract timestamps with built in Date functions. There is no way to do this without writing a lot of code and doing a lot of checks. Also, there is no way to compare 2 times.
Formatting dates is also not available without writing your own code for using third party libraries.
Moment.js solves all of these issues by providing built in functions to do all these common operations. It provides functions for parsing and formatting dates.
momentconstructor is where you can pass in a date string, and a
moment object will be created. For example, you can pass in:
and you will get back a
moment which you can compare with other
moment objects, and add or subtract by different time spans.
If you do not passing in anything to the
moment constructor, you get the current date and time.
It also takes a second argument. If you want to make sure a date is parsed as a YYYY-MM-DD date, then write
moment(‘2019–08–04’, 'YYYY-MM-DD') . If you don’t know the format of your date or time, then you can pass in an array of possible formats and Moment will pick the right one:
moment('2019–08–04', ['YYYY-MM-DD', 'DD-MM-YYYY']);
After you create a Moment object, then you can do many things like formatting dates:
const a = moment('2019–08–04', 'YYYY-MM-DD').format('MMMM Do YYYY, h:mm:ss a'); console.log(a);// August 4th 2019, 12:00:00 am const b = moment('2019–08–04', 'YYYY-MM-DD').format('dddd'); console.log(b); // Sunday const c = moment('2019–08–04', 'YYYY-MM-DD').format("MMM Do YY"); console.log(c); // Aug 4th 19 const d = moment('2019–08–04', 'YYYY-MM-DD').format('YYYY [escaped] YYYY'); console.log(d); // 2019 const e = moment('2019–08–04', 'YYYY-MM-DD').format(); console.log(e);// 2019-08-04T00:00:00-07:00
From the above examples, we see that we can format dates in pretty much any way we want.
We can also tell what time span a date is relative to another date by writing:
const augDate = moment('2019–08–04', 'YYYY-MM-DD'); const sepDate = moment('2019–09–04', 'YYYY-MM-DD'); console.log(augDate.from(sepDate)); // a month ago
We can also add or subtract Moment dates:
const augDate = moment('2019–08–04', 'YYYY-MM-DD'); const sepDate = moment('2019–09–04', 'YYYY-MM-DD'); console.log(augDate.add(10, 'days').calendar()); // 08/14/2019 console.log(augDate.subtract(10, 'days').calendar()); // 07/25/2019
It is easy to compare 2 dates
moment('2010-01-01').isSame('2010-01-01', 'month'); // true moment('2010-01-01').isSame('2010-05-01', 'day'); // false, different month moment('2008-01-01').isSame('2011-01-01', 'month'); // false, different year
You can also check if a date is has Daylight Saving Time in effect or not:
const augDate = moment('2019–08–04', 'YYYY-MM-DD'); const decDate = moment('2019–12–04', 'YYYY-MM-DD'); console.log(augDate.isDST()) // true console.log(decDate.isDST()) // false
toDate() function on a Moment object.
And there we have it!