Open In App

How to Convert from UTC to Local Time in Moment JS?

Last Updated : 01 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Moment.js is a powerful library for working with dates and times in JavaScript. One common requirement is to convert a date and time from Coordinated Universal Time (UTC) to the local time zone of the user's device. This is especially useful for applications that need to display times in the user's local context.

To use the MomentJS library, 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

These are the following approaches:

Using the local() method

In this approach, we are using the local() method of Moment.js. This method converts the date and time from UTC to the local time zone. This method is simple and straightforward.

Syntax:

moment.utc().local();

Example: Below example uses a local() method in momentJS to convert from UTC to local time.

JavaScript
const moment = require("moment");

let utcTime = moment.utc("2024-07-26T12:00:00Z");
let localTime = utcTime.local();
console.log(
    `Local time for 2024-07-26T12:00:00Z (UTC) is: ${localTime.format(
        "YYYY-MM-DD HH:mm:ss"
    )}`
);

Output:

Local time for 2024-07-26T12:00:00Z (UTC) is: 2024-07-26 17:30:00

Using the utcOffset() Method

In this approach we are using the utcOffset() method which allows us to set a specific UTC offset to convert the time. This method is useful if we need to convert the time to a different time zone, not just the local one.

Syntax:

moment.utc().utcOffset(offset);

Example: Below example uses utcOffset() method in momentJS to convert from UTC to local time.

JavaScript
const moment = require("moment");

let utcTime = moment.utc("2024-07-26T12:00:00Z");
let offsetTime = utcTime.utcOffset(-240);
console.log(
    `Time for 2024-07-26T12:00:00Z (UTC) with offset -240 is: ${offsetTime.format(
        "YYYY-MM-DD HH:mm:ss"
    )}`
);

Output:

Time for 2024-07-26T12:00:00Z (UTC) with offset -240 is: 2024-07-26 08:00:00

Next Article

Similar Reads