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
Continue reading “Create a ISO String from date text input intended for UTC date in JavaScript”