Convert date to ISO 8601 and UTC in JavaScript

ISO 8601 & UTC :

If you are working with date, you should always get aware of these two terms: ISO and UTC. ISO 8601 is a standard used for date-time representation. The way date is represented, the date separators are not the same for all countries. Using ISO 8601, we can convert all times to a similar format. So, if we store the ISO date on the database, it can be converted and represent as we like on the frontend.

UTC is the primary time standard by which the time is regulated at different places. JavaScript provides two different methods to get the ISO 8601 and UTC representation of a date object. In this tutorial, I will show you how to use these methods :

Date.toISOString() :

toISOString method is used to convert one Date object to ISO 8601 string. The output is always in YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ format. Just create one Date object and call this method to get the ISO 8601 representation :

const date = new Date('2019-11-10T03:24:00')

console.log(date.toString())
console.log(date.toISOString())

Output :

Sun Nov 10 2019 03:24:00 GMT+0530 (India Standard Time)
2019-11-09T21:54:00.000Z

Date.toUTCString() :

toUTCString returns the date in string format using the UTC time zone. Prior to ECMAScript 2018, the format of the returned value varies based on the system. The new format is similar to toString.

const date = new Date('2019-11-10T03:24:00')

console.log(date.toString())
console.log(date.toUTCString())

Output :

Sun Nov 10 2019 03:24:00 GMT+0530 (India Standard Time)
Sat, 09 Nov 2019 21:54:00 GMT

toISOString is useful for storing the date in the database and toUTCString is useful for showing the date in UTC format in a human-readable format. Javascript provides a couple of useful methods to work with dates. You can also check the moment.js library for more advanced use cases.

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊