The main purpose of Moment.js is to get the current time in different formats to use them further. The main reason I use it, is to get the current time while making any changes in the db, so that I can change the "LastModifiedOn" property in the db, and create a new row and provide value for "DateCreatedOn" field in db.
Let's get to using the Moment.js in node js application.
For this article, we are going to use the project that we have already created in the following article.
Step 1
Install moment package in the application from npm, using the following command-
npm install moment --save
This will install the moment in the application as well as will save the js for the same.
Step 2: Now, include this js in your app.js, using the code given below:
- var moment = require('moment');
Step 3: The next step is to call this moment variable to get different format values. Some of its examples are shown here:
A complete table, for all the moment inputs and their corresponding outputs, is stated below,
S.No
|
Moment Input
|
Output
|
1
|
moment().format('MMMM Do YYYY, h:mm:ss a')
|
July 8th 2016, 11:54:56 pm
|
2
|
moment().format('dddd')
|
Friday
|
3
|
moment().format("MMM Do YY")
|
Jul 8th 16
|
4
|
moment().format()
|
2016-07-08T23:54:56+05:30
|
5
|
moment("20111031", "YYYYMMDD").fromNow()
|
5 years ago
|
6
|
moment("20180620", "YYYYMMDD").fromNow()
|
in 2 years
|
7
|
moment().startOf('day').fromNow()
|
a day ago
|
8
|
moment().endOf('day').fromNow()
|
in 5 minutes
|
9
|
moment().startOf('hour').fromNow()
|
an hour ago
|
10
|
moment().subtract(10, 'days').calendar()
|
06/28/2016
|
11
|
moment().calendar()
|
Today at 11:54 PM
|
12
|
moment().add(1, 'days').calendar()
|
Tomorrow at 11:54 PM
|
13
|
moment.locale()
|
En
|
14
|
moment().format('LT')
|
11:54 PM
|
15
|
moment().format('LTS')
|
11:54:56 PM
|
16
|
moment().format('L')
|
07/08/2016
|
17
|
moment().format('l')
|
7/8/2016
|
18
|
moment().format('LL')
|
July 8, 2016
|
19
|
moment().format('ll')
|
Jul 8, 2016
|
20
|
moment().format('LLL')
|
July 8, 2016 11:54 PM
|
21
|
moment().format('lll')
|
Jul 8, 2016 11:54 PM
|
22
|
moment().format('LLLL')
|
Friday, July 8, 2016 11:54 PM
|
23
|
moment().format('llll')
|
Fri, Jul 8, 2016 11:54 PM
|
|
|
|
Hope, this article helps you in showing or using the current time in your application.