Open In App

Moment.js using with Node.js

Last Updated : 26 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Moment.js simplifies date manipulation in Node.js by providing a powerful library for parsing, validating, manipulating, and formatting dates. It enhances handling time related operations, making complex date tasks straightforward and efficient.

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

dependency in package.json

"dependencies": {
"moment": "^2.30.1",
}

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 using moment.js 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.

Node
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.

Node
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:



Next Article

Similar Reads