Categories
JavaScript Answers

How to convert from UTC to desired time zone with MomentJS and JavaScript?

Spread the love

To convert from UTC to desired time zone with MomentJS and JavaScript, we can use the moment-timezone library.

To use it, we write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.34/moment-timezone.min.js" ></script>

to add the moment.js and moment-timezone scripts.

Then we write:

moment.tz.add([
  'America/New_York|EST EDT|50 40|0101|1Lz50 1zb0 Op0'
]);

const d = new Date(2022, 5, 1);
const myTimezone = "America/New_York";
const myDatetimeFormat = "YYYY-MM-DD hh:mm:ss a z";
const myDatetimeString = moment(d).tz(myTimezone).format(myDatetimeFormat);
console.log(myDatetimeString)

to call moment.tz.add to add the time zone data for Eastern time.

Then we create a date d with the Date constructor.

Next, we call moment with d to create a moment object.

Then we call tz with myTimezone to convert the time to the given time zone.

Next, we call format to return a date string with the format specified by myDatetimeFormat.

Therefore, myDatetimeString is '2022-06-01 03:00:00 am EDT'.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.