Reputation: 33683
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).
Upvotes: 4
Views: 13129
Reputation: 834
You can use the vanilla javascript class called Intl.
const newDate = new Date();
console.log(new Intl.DateTimeFormat('en-us', { dateStyle: 'short', timeStyle: 'medium' }).format(newDate))
;
Upvotes: 0
Reputation: 116
Taking help from this StackOverflow answer, this can be done as follows. You were almost there. toLocaleString()
is the method that you want. As the name suggests, it returns a string so it needs to be converted back into a date object. I think the bulkiness of doing this is why a lot of people prefer using a library like moment.
new Date(
new Date("2021-01-01T00:00:00")
.toLocaleString("en-US", {timeZone: "America/New_York"})
).toISOString();
Upvotes: 4