Open In App

Moment.js using with Node.js

Last Updated : 29 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Moment.js is a date library for JavaScript that parses, validates, manipulates, and formats dates. In this article, we are going to see how we can use moment.js in node.js. Before using moment.js, we must ensure that we have installed the library. We can do so by using the following command.

Installing Moment.js in Node.js:

npm i moment

For using Moment.js, you will need to import it into your project. This can be done in 2 ways:

1. Using the ES6 Style:

import moment from 'moment';

2. Using the require() style:

const moment = require('moment');

You are now all set to use moment.js in your node.js applications. The examples below will help demonstrate the library use in Node.js:

Example 1: This is a code snippet that is used to date and time zone of the current day. It uses the ES6 style for importing the library.

Javascript




import moment from 'moment';
  
let today = moment();
console.log(
    `Today is: ${today.format('L')}`
);
console.log(
    `Timezone is: ${today.utcOffset()} minutes ahead of GMT`
);


Output:

 

Example 2: This example uses the require() style for importing the library.

Javascript




const moment = require('moment');
  
let obj = {
    year: 2022, month: 6, day: 17,
    minutes: 10, second: 7, milliseconds: 55
};
let date = moment(obj);
console.log(
    date.format("dddd, Do MMM YYYY, h:mm:ss A")
 );


Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads