About Moment.js in Javascript




Moment.js is a javascript date library for manipulating, validating, parsing and formatting dates. It makes developer's life easy with it's date formatting capabilities. You can format the date in your required format just with a function without writing tens of lines of code. It works both in Javascript and NodeJs.

FunctionDescription
moment(...)Local mode. It is aDefault mode.
moment.utc(...)utc mode.
moment.parseZone()It keeps the input zone passed in. If the input is ambiguous, then it is assumed to be local mode.
moment.tz(...)can parse input in a specific time zone

This post explains you to how to use moment.js in Node.js or javascript applications.

How to install Moment.js

npm i moment

How to format a input date

Example to print today's date and timestamp

const moment = require('moment');

let timestamp = moment();
console.log(timestamp.format()); // prints current timestamp i.e., 2020-02-17T22:16:02+05:30

The above format is ISO standard where date and time are seperated by T and ended with time-zone.

You can format the date the way you want as MomentJs provide wide number of options.
For example,

moment().format('MMMM Do YYYY, h:mm:ss a'); // April 27th 2020, 6:10:43 pm
moment().format('dddd');                    // Monday
moment().format("MMM Do YY");               // Apr 27th 20

You can also get relative time like below:

moment("20111231", "YYYYMMDD").fromNow(); // 8 years ago
moment("20150604", "YYYYMMDD").fromNow(); // 5 years ago
moment().startOf('day').fromNow();        // 15 hours ago
moment().endOf('day').fromNow();          // in 9 hours
moment().startOf('hour').fromNow();      // 30 minutes ago

Get Calender time like below:

moment().subtract(10, 'days').calendar(); // 04/17/2020
moment().subtract(1, 'days').calendar();  // Yesterday at 6:15 PM
moment().calendar();                      // Today at 6:15 PM
moment().add(1, 'days').calendar();       // Tomorrow at 6:15 PM
moment().add(3, 'days').calendar();       // Thursday at 6:15 PM

It also provide multiple locale support

moment.locale();
moment().format('LL');   // 27 April 2020
moment().format('ll');   // 27 Apr 2020
moment().format('LLLL'); // Monday, 27 April 2020 18:19

Reference from MomentJS