Open In App

Moment.js moment().local() Method

Improve
Improve
Like Article
Like
Save
Share
Report

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

Syntax:

moment().local( 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().local() Method.

Example 1:

Javascript




const moment = require('moment');
  
let nowMoment = moment.utc();
  
console.log(
    "Current Moment is:", nowMoment.toString()
)
console.log(
    "Current Hours:", nowMoment.hours()
)
console.log(
    "Current Minutes:", nowMoment.minutes()
)
  
// Set the Time to display in the local timezone
nowMoment.local()
  
console.log(
    "Current Moment is:", nowMoment.toString()
)
console.log(
    "Current Hours:", nowMoment.hours()
)
console.log(
    "Current Minutes:", nowMoment.minutes()
)


Output:

Current Moment is: Sun Jul 24 2022 17:47:57 GMT+0000
Current Hours: 17
Current Minutes: 47
Current Moment is: Sun Jul 24 2022 23:17:57 GMT+0530
Current Hours: 23
Current Minutes: 17

Example 2:

Javascript




const moment = require('moment');
  
let nowMoment2 = moment(
    "2001-07-05T05:01:27"
).locale("br");
  
console.log(
    "Current Moment is:", nowMoment2.toString()
)
console.log(
    "Current Hours:", nowMoment2.hours()
)
console.log(
    "Current Minutes:", nowMoment2.minutes()
)
  
// Change only the timezone and not the actual
// time of the Moment 
nowMoment2.local(true)
  
console.log(
    "Current Moment is:", nowMoment2.toString()
)
console.log(
    "Current Hours:", nowMoment2.hours()
)
console.log(
    "Current Minutes:", nowMoment2.minutes()
)


Output:

Current Moment is: Thu Jul 05 2001 05:01:27 GMT+0530
Current Hours: 5
Current Minutes: 1
Current Moment is: Thu Jul 05 2001 05:01:27 GMT+0530
Current Hours: 5
Current Minutes: 1

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



Last Updated : 26 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads