Explain Codes LogoExplain Codes Logo

How to convert a Date to UTC?

javascript
date-conversion
timezone-handling
moment-js
Alex KataevbyAlex Kataev·Sep 3, 2024
TLDR

Need a speedy fix? Turn a Date object into UTC with the toISOString command:

let utcDate = new Date().toISOString();

Simple, right? This affords you an instantaneous conversion into a UTC string.

Date conversion techniques

If toISOString isn't enough, there's more! Use a combo of Date.UTC and getTimezoneOffset for a hands-on approach to UTC:

// Hey, borrow time from the future! let date = new Date(); let utcDate = new Date(date.getTime() + date.getTimezoneOffset() * 60000);

We're compensating the local time with the timezone offset, ultimately landing us on that sweet UTC.

Handling daylight saving and timezone snags

Fear the wrath of daylight saving and timezones no more, Date.UTC is here to the rescue:

let utcDate = new Date(Date.UTC(year, month, day, hour, minute, second));

This rescues us from the treacherous pitfalls of daylight saving and timezone changes. No more losing sleep over lost hours!

Robust handling with Moment.js

Should your project require a heavy-duty approach to time handling, look no further than Moment.js:

let utcDate = moment(date).utc().format();

Moment.js adjusts its tie, clears its throat, and seamlessly transitions your local time to UTC.

Got an old browser? No problem!

What about older browsers without toISOString, you ask? Never fear, a handy shim is here:

if (!Date.prototype.toISOString) { // Now's the time to roll up your sleeves and make your own toISOString! }

Unsupported browsers will be a worry of the past.

Testing timezone conversions - Safety first!

To ensure that your conversions are on point, comprehensive testing is key:

console.assert(new Date('2023-01-01T12:00:00Z').getTime() === new Date(Date.UTC(2023, 0, 1, 12)).getTime()); // These better be the same. Otherwise, blame 2022 for not being 2023 yet.

Keep testing until you're sure your application won't mix-up Auckland with Arizona.

Handling UTC parsing at the server-side

When parsing date and time strings, the server-side needs consistent handling:

let serverDate = moment.utc('2023-01-01T12:00:00+02:00').toDate(); // Let's go travel in time, shall we?

By using the UTC at the server-side, you're one step closer to banishing timezone inconsistencies.