The open blogging platform. Say no to algorithms and paywalls.

It is really easy to convert local time to UTC in JavaScript

Do you feel the need for a library even for a small task like converting local Date to UTC format?

When I first came into the world of JavaScript dates, I felt the same. And today I am here to tell you, most of the things you’re trying to achieve with dates can be done with the native Date constructor given by Javascript. So let’s start…

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:

  1. new Date(year, month, date, hours, minutes, seconds, ms)

  2. new Date(“July 29, 2019 04:00:00”) // Date string

  3. new Date(“2019–07–29”) // YYYY-MM-DD

  4. new Date(“07/29/2019”) // MM/DD/YYYY

  5. 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.

image

Now, what if you want the current time in UTC format. Well, thanks to Javascript Date constructor. You simply need to keep the arguments field blank while calling the Date function. So

    new Date();

    // would essentially give you the current time

    new Date().toISOString();

    // would give you the current time in ISO format

Conclusion

The new Date constructor in Javascript has a whole lot of methods that we can use for most of our date manipulations, and there is no need to use an external library like momentjs for this purpose unless you would want special manipulations like figuring out the time difference between two dates and etc. Also, those libraries are heavy and would only reduce your performance unless used effectively and when strictly needed.




Continue Learning