Let’s say that you receive a date like “14/01/2022”, “14 January 2022”, “Jan, 14 2022” etc, and you need to convert this date to an ISO string in JavaScript while ensuring that the date that is inputted is for UTC (Universal Time Coordinated) timezone – no matter where you are in the world. It would seem easy right?
Your first reaction might be to simply do something like this:
1 2 3 |
const dateString = "14 Jan 2022"; // U.S. peeps <em>"Jan, 14 2022"</em> const IsoDateString = new Date(dateString).toISOString(); |
Now unless you are sitting smack-dab in a UTC timezone you might be in for a bit of a surprise.
Right now, my timezone is UTC+11 hours. This means that my result of the code in the example above will report the previous day at 1pm UTC.
1 2 3 |
console.log(IsoDateString); //RESULT: 2022-01-13T13:00:00.000Z |
That’s not what I am looking for all. I need to set this date to precisely midnight of 14 Jan 2022 UTC time.
2022-01-14T00:00:00.000Z
The Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
/** * Generates a UTC zoned ISO formatted date string. * @param {string} dateString - Text string containing an accepted date format. * @returns {date} ISO string formatted date for UTC time. */ function createUTCdateForISO(dateString) { const offset = new Date().getTimezoneOffset(); const myDate = Date.parse(dateString) - (offset * 60 * 1000); const dateAsISO = new Date(myDate).toISOString(); return dateAsISO; } //Example formats console.table([ createUTCdateForISO("Jan 14, 2022"), createUTCdateForISO("01/14/2022"), createUTCdateForISO("14 Jan 2022"), ]); |
Note! Parsing an ISO format (e.g. “2022-01-14”) using this approach will not work because it will already be set to UTC. Simply use new Date(dateString).toISOString();
in this case.
Table of Contents
Tested in Chrome and Node.js.
Get your timezone offset
Line 7
First, we need to get the current timezone offset that you are working in. We can do this with the JavaScript Date getTimeZoneOffset()
method.
Why not just manually add 11 hours to the date? Well, two reasons come to mind:
- There is daylight saving where I am currently working in so this offset will change to +10 in wintertime.
- What if this code is to be used from different locations? We want all locations to be able to set a date to UTC time.
The getTimeZoneOffset()
method returns the amount of time offset from UTC in minutes. So for example, our timezone is +11 hrs from UTC so:
UCT 0hrs - UTC+11hrs = -11hrs.
-11hrs x 60 minutes = -660 minutes.
Converting the Date String to UTC time
Line 8
Now that we have our offset, we can use the JavaScript Date.parse method to create our local date in milliseconds and add the offset, converted to milliseconds to set the date in UTC time.
Date.parse(dateString) - (offset * 60 * 1000);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
console.table([ ["Local Date in Milliseconds: ", Date.parse("Jan 14, 2022")], ["Timezone offest in minutes: ", new Date().getTimezoneOffset()], [ "Timezone offset in milliseconds: ", new Date().getTimezoneOffset() * (60 * 1000), ], [ "UTC time in Milliseconds", Date.parse("Jan 14, 2022") - new Date().getTimezoneOffset() * 60 * 1000, ], ]); // Results ┌─────────┬─────────────────────────────────────┬───────────────┐ │ (index) │ 0 │ 1 │ ├─────────┼─────────────────────────────────────┼───────────────┤ │ 0 │ 'Local Date in Milliseconds: ' │ 1642078800000 │ │ 1 │ 'Timezone offest in minutes: ' │ -660 │ │ 2 │ 'Timezone offset in milliseconds: ' │ -39600000 │ │ 3 │ 'UTC time in Milliseconds' │ 1642118400000 │ └─────────┴─────────────────────────────────────┴───────────────┘ |
Note! You could alternatively use the new Date()
constructor instead of the date parse method here. However, the date parse approach did run a little faster on a JavaScript benchmark test.
Convert UTC date in milliseconds to ISO date.
Line 9
Finally, we can use the toISOString()
method to convert the UTC date in milliseconds to a readable string.
1 2 3 |
new Date(myDate).toISOString(); // '2022-01-14T00:00:00.000Z' |
Finally, the ISO string is returned from the function.
The video tutorial
Conclusion
The above is a rather unusual situation. More often than not you will be receiving or generating a proper date format rather than date text strings. Likewise, you generally won’t need to get a UTC time based on a current date either.
In my research for this post, I did find that there is an approach to use Date.UTC(year, month, day), but that would require a lot more code to identify years months and days in non-uniform dates and then split them and add them to the UTC arguments. So I abandoned it.
It would be cool to hear how you use this to solve a problem in your own project? Was it unavoidable? Did you discover a different way?
Feel free to comment below.
Need help with Google Workspace development?
My team of experts can help you with all of your needs, from custom app development to integrations and security. We have a proven track record of success in helping businesses of all sizes get the most out of Google Workspace.
Schedule a free consultation today to discuss your needs and get started or learn more about our services here.
~Yagi