JavaScript - 获取系统短日期格式 [英] JavaScript - Get system short date format

查看:180
本文介绍了JavaScript - 获取系统短日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



有没有办法在JavaScript中获取系统的日期格式?例如,系统的短日期是否为美国格式,例如。 m / d / Y或欧洲例如。 d / m / Y



请注意:
这不是关于格式化日期或基于地理位置计算的问题,而是从OS /系统获取格式

解决方案

经过一番研究,我得出结论,在技术上,不可能获得区域设置 - 这样,日期格式 - 但你可以做其他几件事情。选择以下选项之一:
a)已经提到的和已过期的toLocaleString()函数:

  var myDate = new Date(1950,01,21,22,23,24,225); 
var myDateFormat = myDate.toLocaleString();
alert(myDateFormat);

问题:
1)你不能myDateFormat.replace获取日期掩码,因为月份不是作为字符串中的01,02等存储,而是作为文本而不是基于区域设置(如2月在英语中,但它是Φεβρουάριος在希腊语,谁知道什么
2)不同浏览器上的不同行为
3)不同操作系统和浏览器版本上的不同行为...

b)使用 toISOString()函数,而不是 toLocaleString()。您将无法获取区域设置日期面罩,但可以从中指定日期,从中可以知道日期的哪个部分(即该字符串中的月或日)。您还可以使用 getUTCDate() getUTCMonth() getUTCDay()函数。您仍然无法知道客户端使用哪种日期格式,但是可以告诉您在获取日期时使用哪个年/月/日/ etc?使用上面的代码来测试我在这里提到的功能,看看你可以期待什么。

c)阅读
不同浏览器中的toLocaleString()的不一致行为文章,并使用(IMHO伟大)解决方案


Is there any way to get system short date format in JavaScript?

For example whether system's short date is in American format eg. m/d/Y or in european eg. d/m/Y

Please note: This is not question about formatting date or calculating it based on geolocation, but about getting the format from the OS/system

解决方案

After a pinch of research I concluded that technically it's not possible to get regional settings -and by this, date format- but you can do several other things. Pick one of these options:
a) The already mentioned -and outdated- "toLocaleString()" function:

var myDate = new Date(1950, 01, 21, 22, 23, 24, 225);
var myDateFormat = myDate.toLocaleString();
alert (myDateFormat);

ISSUES:
1) You can't "myDateFormat.replace" to get the date mask as month is not stored as "01", "02", etc in the string but as text instead, based on locale (like "February" in English but it's "Φεβρουάριος" in Greek and who knows what in e.g. Klingon).
2) Different behavior on different browsers
3) Different behavior on different OS and browser versions...

b) Use the toISOString() function instead of toLocaleString(). You won't get the locale date mask but get a date from which you can tell where's which part of the date (ie where "month" or "day" is in that string). You can also work with getUTCDate(), getUTCMonth() and getUTCDay() functions. You still can't tell what date format the client uses, but can tell which Year/Month/Day/etc you work with when you grab a date; use the code above to test the functions I mentioned here to see what you can expect.

c) Read Inconsistent behavior of toLocaleString() in different browser article and use the (IMHO great) solution described there

这篇关于JavaScript - 获取系统短日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆