convert utc time to local time moment

Converting UTC Time to Local Time Using Moment.js Library

As a blogger and a web developer, I have come across situations where I had to convert UTC time to local time for displaying it to the users of my website. This can be done using JavaScript libraries such as Moment.js, which provides easy-to-use and efficient functions for handling dates and times.

Step-by-Step Guide

  • Step 1: Install the Moment.js library by adding the following script tag to your HTML file:

  • Step 2: Get the UTC time that needs to be converted. This can be done using JavaScript's built-in Date() constructor.

let utcTime = new Date('2022-01-01T00:00:00Z');
  • Step 3: Use the Moment.js library's utc() method to convert the UTC time to a Moment.js object.

let localTime = moment.utc(utcTime);
  • Step 4: Use the Moment.js library's local() method to convert the Moment.js object to local time.


The above code will return a Moment.js object that represents the local time equivalent of the UTC time passed in the utc() method.

Alternative Method

Another way to convert UTC time to local time is to use JavaScript's built-in methods. The following code demonstrates this:

let utcTime = new Date('2022-01-01T00:00:00Z');
let localTime = new Date(utcTime.getTime() - utcTime.getTimezoneOffset() * 60000);

The above code subtracts the local timezone offset from the UTC time to get the local time equivalent. However, this method is not as efficient as using Moment.js, especially when dealing with complex date/time calculations.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]