I want to convert a date time string with a specific locale (locale defined in IANA format) to a Date
object and print UTC time in ISO 8601 format. This code below works perfectly.
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', ()=>{
console.log(moment('2021-01-01T00:00:00').tz('America/New_York').toISOString());
});
</script>
The result is my console log shows 2021-01-01T05:00:00.000Z
.
However, I want to achieve the same result without using any 3rd party libraries. I only want to use the browser's Javascript default objects/classes/apis etc... So I tried all of these but they all gave errors:
new Date("2021-01-01T00:00:00 America/New_York").toISOString();
(new Date("2021-01-01T00:00:00")).setLocale('America/New_York').toISOString();
(new Date("January 1, 2021 12:00:00 AM America/New_York").toISOString();
What is the correct way in javascript to convert a date string with a locale to ISO 8601 format without the use of javascript libraries like moment, luxon, etc...?
I need it to work in any Desktop version of Chrome, FireFox, Edge and Safari released after January 1, 2021 (support not needed for older versions).