简体   繁体   中英

How to convert date string with specific locale to ISO format

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

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();

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))

;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM