How to convert MomentJS Date to Users Local Timezone?



Sometimes, when doing a project for a specific organization in a particular country, we need to convert it into the users' local timezone. In this article, we are going to learn how to convert a date to a user's local timezone using moment.js.

Prerequisite

  • Moment.js: Moment.js is a popular JavaScript library used for dealing with dates. This library is used to modify, parse, validate, manipulate, and display dates and times in JavaScript. MomentJS works with UTC (Coordinated Universal Time) by default or any other specific time zone.
Install Moment.js:
npm install moment

Approaches to convert MomentJS Date to User Local Timezone

Using MomentJS with Moment Timezone Plugin

First, import the MomentJS and Timezone plugins. Now input a date string like 2024-12-12T10:00:00Z. Then use moment.tz.guess() to automatically determine the user's timezone based on their system. Now use the tz() method to convert the UTC date to the user's timezone. Finally, format the output so that it is readable to the user.

Example

// Import MomentJS and Timezone plugin
const moment = require('moment-timezone');

// Example UTC Date
const utcDate = "2024-12-12T10:00:00Z";

// Convert to User's Local Timezone
const localDate = moment(utcDate).tz(moment.tz.guess()).format('YYYY-MM-DD HH:mm:ss');

// Print the result
console.log("Local Timezone Date:", localDate);
Local Timezone Date: 2024-12-12 15:30:00

Using MomentJS without Moment Timezone Plugin

We first import the MomentJS library. Now, specify the date and time in UTC format that we want to convert to the local timezone. Now, use moment.utc() to parse the UTC date. Then call the local() method to convert it to the local timezone. Finally, format the output which is readable to the user.

Example

// Example UTC Date
const utcDate = "2024-12-12T10:00:00Z";

// Get Local Time
const localDate = moment.utc(utcDate).local().format('YYYY-MM-DD HH:mm:ss');

// Print the result
console.log("Local Timezone Date:", localDate);

Output

Local Timezone Date: 2024-12-12 15:30:00

Using the above two methods we can convert the moment.js date to User's local timezone. Both methods are efficient. We can use any method depending on our choice.

Updated on: 2024-12-24T10:08:08+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements