Javascript Convert Date to UTC

Oct 24, 2019

In the following example, it will convert the date format from UTC to local timezone

const date = new Date('2019-10-18T00:00:00.000000Z')// note that local timezone is applied to the date, thus +8 hoursdate.toString() // Fri Oct 18 2019 08:00:00 GMT+0800 (Malaysia Time)

You can still get UTC Date String from the local date

date.toUTCString() // Fri, 18 Oct 2019 00:00:00 GMT

How do we get a Date object which show the date as UTC?

Solution 1

// remove the trailing Zconst date = new Date('2019-10-18T00:00:00.000000')// it treat the string as local date (not UTC), and convert to date exactly as it is without +8 hours// sadly, but it will still show timezone as GMT+0800 (Malaysia Time), not UTCdate.toString() // Fri Oct 18 2019 00:00:00 GMT+0800 (Malaysia Time)

NOTE: I could not find a way to create a date which show timezone as GMT+0000 (UTC)

Solution 2

If you just need to print the date as UTC, use toLocaleDateString with 'timeZone': 'UTC'.

const date = new Date('2019-10-18T00:00:00.000000Z')date.toUTCString() // Fri, 18 Oct 2019 00:00:00 GMTvar options = { year: 'numeric', month: 'short', day: 'numeric', 'hour': 'numeric', 'timeZone': 'UTC' };date.toLocaleDateString('en-US', options) // Oct 18, 2019, 12 AM

Solution 3

const date = new Date('2019-10-18T00:00:00.000000Z')// convert 'Fri, 18 Oct 2019 00:00:00' to Dateconst utcDate = new Date(date.toUTCString().substr(0, 25))// or// const utcDate = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds())date.toString() // Fri Oct 18 2019 00:00:00 GMT+0800 (Malaysia Time)

Solution 4

Use Moment.js

moment.utc('2019-10-18T00:00:00.000000Z').format() // 2019-10-18T00:00:00Z

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.