英文:
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);
从中,你可以将其转换为所需格式。可能需要更改 dateStyle
或 timeStyle
选项。
替代方案
然而,正如评论中所指出的,我建议不要在后端或数据库端处理时区和日期格式,而是在那里使用 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: 'short', timeStyle: 'short' }
).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('2023-03-31T09:31:47.362Z');
const intlDateTimeFormat = new Intl.DateTimeFormat(undefined,
{ dateStyle: 'short', timeStyle: 'short' });
const formattedDate = intlDateTimeFormat.format(myDate);
console.log(formattedDate);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论