查找在JS中使用的日期格式(d/m/Y…)和时间格式。

huangapple go评论64阅读模式
英文:

Find used dateformat (d/m/Y..." and timeformat in JS

问题

我正在尝试找到时区,日期格式(d.m.Y,Y/m/d,...)和时间格式(H:i,h:i A,...)。

我使用 Intl.DateTimeFormat().resolvedOptions().timeZone 获取时区... 但如何获取其他数据?

我通过 XMLHttpRequest 将数据传递给 PHP,然后希望在那里指定日期和时间格式。

英文:

I am trying to find the time zone, the date format (d.m.Y, Y/m/d,...) and the time format (H:i, h:i A,...).

I get the time zone with Intl.DateTimeFormat().resolvedOptions().timeZone... But how do I get the other data?

I pass the data to PHP with an XMLHttpRequest and want to specify the date and time format there afterwards.

答案1

得分: 1

解决方案

无法直接获得所需输出的日期格式,因为它不是标准化的,但可以使用 formatToParts() 来获取不同部分的值分割:

const parts = new Intl.DateTimeFormat(undefined,
  { dateStyle: 'short', timeStyle: 'short' }
).formatToParts();
console.log(parts);

从中,你可以将其转换为所需格式。可能需要更改 dateStyletimeStyle 选项。

替代方案

然而,正如评论中所指出的,我建议不要在后端或数据库端处理时区和日期格式,而是在那里使用 ISO 日期字符串。要格式化日期,可以使用 format 函数:

const myDate = new Date('2023-03-31T09:31:47.362Z');
const intlDateTimeFormat = new Intl.DateTimeFormat(undefined,
  { dateStyle: 'short', timeStyle: 'short' });
const formattedDate = intlDateTimeFormat.format(myDate);
console.log(formattedDate);
英文:

Solution

There is no way to get the date format in your desired output because it's not standardized, but you can use formatToParts() to get the value split up in the different parts:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const parts = new Intl.DateTimeFormat(undefined,
  { dateStyle: &#39;short&#39;, timeStyle: &#39;short&#39; }
).formatToParts();
console.log(parts);

<!-- end snippet -->

From this you can transform it into your desired format. You may need to change the dateStyle or timeStyle options.

Alternative

However, as pointed out in the comments, I would recommend not to deal with time zones and date formats on backend or database side, but rather work there with ISO date strings. To format a date, you can use the format function:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const myDate = new Date(&#39;2023-03-31T09:31:47.362Z&#39;);
const intlDateTimeFormat = new Intl.DateTimeFormat(undefined,
  { dateStyle: &#39;short&#39;, timeStyle: &#39;short&#39; });
const formattedDate = intlDateTimeFormat.format(myDate);
console.log(formattedDate);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月31日 15:50:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75896085.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定