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
How to Set Up Cron Jobs in Linux
How to build a Discord bot using TypeScript
Getting Started with Deno
How to deploy a Node app using Docker
Learn how to use v-model with a custom Vue component
Getting Started with Moment.js
Learn how to build a Slack Bot using Node.js
Building a Real-Time Note-Taking App with Vue and Firebase
Getting Started with React
Setting Up Stylus CSS Preprocessor
