Open In App

Moment.js moment().utc() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The moment().utc() method is used to specify that the given Moment object’s timezone would be displayed as UTC. An optional parameter can be passed that preserves the current time value and only changes the timezone to UTC.

Syntax:

moment().utc( Boolean );

Parameters:

  • Boolean: It is a boolean value that specifies whether the timezone would be changed without changing the actual time itself.

Return Value:

This method returns the Moment object with the new timezone.

Note: This will not work in the normal Node.js program because it requires an external moment.js library to be installed globally or in the project directory.

Steps to Install the Node App:

Step 1: Run the following commands to initialize the project and create an index file & env file. (Make sure you have node and npm installed)

npm init -y

Step 2: Installing required packages

npm install moment

Project Structure:

The updated dependencies in package.json file will look like:

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

Example 1: This example shows the use of moment and printing the time in the console.

Javascript




const moment = require('moment');
 
let momentOne = moment();
console.log(
    "MomentOne is:", momentOne.toString()
);
console.log(
    "MomentOne hours:", momentOne.hours())
;
console.log(
    "MomentOne minutes:", momentOne.minutes()
);
 
// Display utc format of the Moment
momentOne.utc()
 
console.log(
    "MomentOne is:", momentOne.toString()
);
console.log(
    "MomentOne hours in UTC:", momentOne.hours()
);
console.log(
    "MomentOne minutes in UTC:", momentOne.minutes()
);


Output:

MomentOne is: Tue Nov 21 2023 14:07:18 GMT+0000
MomentOne hours: 14
MomentOne minutes: 7
MomentOne is: Tue Nov 21 2023 14:07:18 GMT+0000
MomentOne hours in UTC: 14
MomentOne minutes in UTC: 7

Example 2: This example shows the use of moment and printing the time in the console.

Javascript




const moment = require('moment');
 
let momentTwo = moment();
console.log(
    "MomentTwo is:", momentTwo.toString()
);
console.log(
    "MomentTwo hours:", momentTwo.hours())
;
console.log(
    "MomentTwo minutes:", momentTwo.minutes()
);
 
// Change the timezone flag, without changing the time
// by passing the Boolean value to true
momentTwo.utc(true)
 
console.log(
    "MomentTwo is:", momentTwo.toString()
);
console.log(
    "MomentTwo hours in UTC:", momentTwo.hours()
);
console.log(
    "MomentTwo minutes in UTC:", momentTwo.minutes()
);


Output:

MomentTwo is: Tue Nov 21 2023 14:07:49 GMT+0000
MomentTwo hours: 14
MomentTwo minutes: 7
MomentTwo is: Tue Nov 21 2023 14:07:49 GMT+0000
MomentTwo hours in UTC: 14
MomentTwo minutes in UTC: 7


Last Updated : 05 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads