本文介绍了如何根据用户区域设置设置数字和日期的格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一种根据用户的语言环境设置自动设置日期和数字对象格式的方法.
到目前为止,我一直在使用toLocaleString()
函数作为日期.对于数字,也可以使用toLocaleString()
,但是正如您已经在我准备的 jsFiddle 中看到的那样不同的浏览器之间差异很大.在Windows计算机上使用英语(美国)语言环境,我得到以下信息:
- IE9:15,000.00
- Firefox:15,000
- Chrome:15000
在Chrome中,toLocaleString()
对于数字似乎根本不起作用.除了这种方法,我还尝试过:
- 要使用MicrosoftAjax.js库
localeFormat()
函数,但是无论我在PC上设置了哪种语言环境(通过使用区域和语言"对话框),日期和数字仍然都是美国格式. li>- 使用全球化之类的库.尽管它们确实提供了格式化功能,但是它们无法自动检测用户的语言环境.
因此,总结一下:如何自动设置数字和日期的格式,以尊重在所有主要浏览器(IE,Firefox,Chrome)中都可以使用的方式浏览网页的用户的区域设置?
本机Javascript对象上的
解决方案
.toLocaleString()
函数实际上是无用的,因为它不允许您指定语言环境或控制其行为.
直到 ECMAScript i18n API 成为现实(将来可能太过遥远,现在就不值得考虑了),您唯一可行的选择是使用诸如Globalize之类的库,但是正如您所说的,您需要检测用户的首选语言环境.
检测语言环境是另一个问题,使用纯Javascript很难解决.具体来说,Accept-Language
标头实际上对恕我直言毫无用处,因为它对于绝大多数Web用户都不可见,因为它无法进行区域设置检测.因此,Web应用程序通常为用户提供一种自定义机制,以供用户选择传递回服务器的语言环境,然后服务器使用此信息来配置此后的每个响应.
I need a way to automatically format Date and Number objects based on locale settings of my users.
So far, I've been using toLocaleString()
function for dates. For numbers, toLocaleString()
is also available, but as you can see in the jsFiddle I've prepared, results vary greatly between browsers. With English (United States) locale on my Windows machine, I get this:
- IE9: 15,000.00
- Firefox: 15,000
- Chrome: 15000
In Chrome, it seems like toLocaleString()
does not work at all for numbers. Except this approach, I've also tried:
- To use MicrosoftAjax.js library
localeFormat()
function, but no matter which locale I've set on my PC (by using "Region and Language" dialog), dates and numbers were still both formated in US format. - To use libraries like Globalize. Although they do offer formatting capabilities, they are not able to detect user's locale automatically.
So, to summarize: how to automatically format numbers and dates to respect regional settings of user that browses the webpage in a way that works in all major browsers (IE, Firefox, Chrome)?
解决方案
.toLocaleString()
functions on native Javascript objects is practically useless because it does not let you specify the locale or otherwise control their behavior.
Until the ECMAScript i18n API becomes a reality (which is probably too far in the future to be worth considering at all right now) your only practical option is using libraries such as Globalize, but then as you say you need to detect the user's preferred locale.
Detecting the locale is another problem that is not easily solved with pure Javascript. Specifically, the Accept-Language
header is IMHO practically useless as a means of locale detection because it is not visible to the vast majority of web users. That's why web applications typically provide a custom mechanism for the user to select a locale which is communicated back to the server, and the server uses this information to configure each response thereafter.
这篇关于如何根据用户区域设置设置数字和日期的格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!