How to Convert a Date to UTC String in JavaScript
Table of Contents
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.
JAVASCRIPTconst date = new Date();
Let's log this date so we can see what it looks like.
JAVASCRIPTconst date = new Date();
console.log(date);
BASHSat 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.
JAVASCRIPTconst date = new Date();
console.log(date.toUTCString());
BASHSun, 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:
JAVASCRIPTconst date = new Date(Date.UTC(2022, 6, 17));
console.log(date.toUTCString());
BASHSun, 17 Jul 2022 00:00:00 GMT
Finally, if you need your date in the ISO-8601 format, you can use the toISOString
method.
JAVASCRIPTconst date = new Date(Date.UTC(2022, 6, 17));
console.log(date.toISOString());
BASH2022-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!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js
- Using Axios to Pull Data from a REST API