Skip to content
Related Articles

Related Articles

Moment.js moment().utc() Method

View Discussion
Improve Article
Save Article
  • Last Updated : 26 Jul, 2022
View Discussion
Improve Article
Save Article

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: This method accepts a single parameter as mentioned above and described below:

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

Moment.js can be installed using the following command:

Installation of moment module:

npm install moment

The below examples will demonstrate the Moment.js moment().utc() Method.

Example 1:

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: Sun Jul 24 2022 01:42:42 GMT+0530
MomentOne hours: 1
MomentOne minutes: 42
MomentOne is: Sat Jul 23 2022 20:12:42 GMT+0000
MomentOne hours in UTC: 20
MomentOne minutes in UTC: 12

Example 2:

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: Sun Jul 24 2022 01:42:42 GMT+0530
MomentTwo hours: 1
MomentTwo minutes: 42
MomentTwo is: Sun Jul 24 2022 01:42:42 GMT+0000
MomentTwo hours in UTC: 1
MomentTwo minutes in UTC: 42

Reference: https://momentjs.com/docs/#/manipulating/utc/


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!