Categories
JavaScript Answers

How to convert local time to UTC time with moment.js and JavaScript?

Spread the love

Sometimes, we want to convert local time to UTC time with moment.js and JavaScript.

In this article, we’ll look at how to convert local time to UTC time with moment.js and JavaScript.

How to convert local time to UTC time with moment.js and JavaScript?

To convert local time to UTC time with moment.js and JavaScript, we can use the moment utc and format method.

For instance, we write:

const d = new Date(2022, 1, 1)
const s = moment.utc(d).format("YYYY-MM-DD HH:mm:ss Z")
console.log(s)

to create the date d in local time.

Then we create a UTC moment object from d with moment.utc.

Next, we call format to with a format string that returns the date and time with the time zone.

As a result, s is '2022-02-01 08:00:00 +00:00'.

Conclusion

To convert local time to UTC time with moment.js and JavaScript, we can use the moment utc and format method.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published. Required fields are marked *