Do you feel the need for a library even for a small task like converting local Date to UTC format?
Convert to UTC/ISO
Maybe the most common functionality one would be looking for while working with dates.
To convert any date to ISO format, all you need to do is:
new Date('07/29/2019 04:00:00').toISOString();// "2019-07-28T22:30:00.000Z"
So assuming we want to ISO format of Date: 29th July, 2019 04:00 o’clock
We would call the new Date constructor and pass the date as a parameter. The supported formats are:
- new Date(year, month, date, hours, minutes, seconds, ms)
- new Date(“July 29, 2019 04:00:00”) // Date string
- new Date(“2019–07–29”) // YYYY-MM-DD
- new Date(“07/29/2019”) // MM/DD/YYYY
- new Date(“2019–07–29T04:00:00Z”) // ISO Date
I may miss some, but these are the most used formats especially 1, 3 and 4.
Next, when our date is ready, we can chain various methods to change the format, and one of the methods being “toISOString”.
ISO formats are very popular when it comes to storing date in the database. It ensures all other applications consuming this data is getting same date and not locally converted date. Cause remember your application can have multiple servers located in different timezones. You would not want to store date in local timezone when your server is multinationally distributed.
Another useful method provided by new Date constructor is “toUTCString”.
So when we call .toUTCString it converts the date in UTC format but in more readable form.
new Date('07/29/2019 04:00:00').toUTCString();// "Sun, 28 Jul 2019 22:30:00 GMT"
This method would be helpful in the frontend when you would want your user to show UTC date in a more readable format.
new Date();// would essentially give you the current timenew Date().toISOString();// would give you the current time in ISO format