简体   繁体   English

如何将具有特定语言环境的日期字符串转换为 ISO 格式

[英]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.我想将具有特定语言环境(以 IANA 格式定义的语言环境)的日期时间字符串转换为Date object 并以 ISO 8601 格式打印 UTC 时间。 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 .结果是我的控制台日志显示2021-01-01T05:00:00.000Z

However, I want to achieve the same result without using any 3rd party libraries.但是,我想在不使用任何 3rd 方库的情况下获得相同的结果。 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:我只想使用浏览器的 Javascript 默认对象/类/api等...所以我尝试了所有这些,但它们都给出了错误:

   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...? javascript 中的正确方法是在不使用诸如 moment、luxon 等 javascript 库的情况下将具有区域设置的日期字符串转换为 ISO 8601 格式的正确方法是什么?

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).我需要它在 2021 年 1 月 1 日之后发布的任何桌面版 Chrome、FireFox、Edge 和 Safari 中工作(旧版本不需要支持)。

Taking help from this StackOverflow answer , this can be done as follows.这个 StackOverflow 答案中获取帮助,可以按如下方式完成。 You were almost there.你快到了。 toLocaleString() is the method that you want. toLocaleString()是您想要的方法。 As the name suggests, it returns a string so it needs to be converted back into a date object.顾名思义,它返回一个字符串,因此需要将其转换回日期 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.您可以使用称为 Intl 的普通 javascript class。

 const newDate = new Date();
console.log(new Intl.DateTimeFormat('en-us', { dateStyle: 'short', timeStyle: 'medium' }).format(newDate))

; ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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