Using Moment.js in Node.js
How to integrate Moment.js into your Node.js applications to utilize dates and times in different formats and use cases.
Join the DZone community and get the full member experience.
Join For Freethe main purpose of moment.js is to get the current time in different formats to use them in other ways. the main reason i use it is to get the current time while making any changes in the database, so that i can change the "lastmodifiedon" property in the database and create a new row and provide a value for the "datecreatedon" field in the database.
let's get to using moment.js in a node.js application.
step 1
install moment package in the application from npm, using the following command:
npm install moment --save
this will install moment.js in the application as well as save the js for the same.
step 2
now, include this javascript in your app.js, using the code below:
var moment = require('moment');
step 3
the next step is to call this moment variable to get different format values. some 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.
Opinions expressed by DZone contributors are their own.
Comments