How to convert back to another timezone in moment.js?

Member

by gilbert , in category: Javascript , 8 months ago

How to convert back to another timezone in moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 8 months ago

@gilbert 

To convert a date and time back to another timezone in Moment.js, you can use the moment.tz() method and specify the target timezone as the argument. Here is an example:

1
2
3
4
5
6
7
// Convert current date and time to 'America/New_York' timezone
let dateTime = moment.tz('America/New_York');

// Convert 'America/New_York' timezone back to 'Asia/Tokyo' timezone
let dateTimeTokyo = dateTime.clone().tz('Asia/Tokyo');

console.log(dateTimeTokyo.format('YYYY-MM-DD HH:mm:ss')); // Output: Converted date and time in 'Asia/Tokyo' timezone


In this example, we first create a Moment.js object with the current date and time in the 'America/New_York' timezone. Then, we use the clone() method to create a copy of the Moment.js object and use the tz() method to convert it back to the 'Asia/Tokyo' timezone. Finally, we use the format() method to display the converted date and time in the desired format.