How to Convert a Date to UTC String in JavaScript

Updated onbyAlan Morel
How to Convert a Date to UTC String in JavaScript

Being able to represent date and time properly is very important in programming.

One of the most common ways to represent a date is to use the UTC time zone.

The UTC time zone, or the Coordinated Universal Time, is useful because allows time to be represented in a consistent manner.

In this post, we'll learn how you can convert a date to a UTC string.

Convert a Date to a UTC String

To start off, let's create a date object.

JAVASCRIPT
const date = new Date();

Let's log this date so we can see what it looks like.

JAVASCRIPT
const date = new Date(); console.log(date);
BASH
Sat Jul 16 2022 12:00:00 GMT-0400 (Eastern Daylight Time)

As you can see, the browser will automatically apply your local time zone to the date, in my case, I'm in the Eastern Daylight Time zone.

However, if you use the toUTCString method, you'll get the UTC time zone.

JAVASCRIPT
const date = new Date(); console.log(date.toUTCString());
BASH
Sun, 17 Jul 2022 00:00:00 GMT

You can tell it worked because it even correctly changed the date from 16 to 17 because in UTC, it is already "tomorrow" relative to my current time zone.

Another way to get a UTC string is to use Date.UTC to dynamically create a new date object:

JAVASCRIPT
const date = new Date(Date.UTC(2022, 6, 17)); console.log(date.toUTCString());
BASH
Sun, 17 Jul 2022 00:00:00 GMT

Finally, if you need your date in the ISO-8601 format, you can use the toISOString method.

JAVASCRIPT
const date = new Date(Date.UTC(2022, 6, 17)); console.log(date.toISOString());
BASH
2022-07-17T00:00:00.000Z

In general, it will return the date in the format YYYY-MM-DDTHH:MM:SS.000Z.

Conclusion

In this post, we looked at how to convert a date to a UTC string.

We also looked at how to create a date object using the Date.UTC method and how to output dates in the ISO-8601 format.

Thanks for reading and happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.