在 javascript 中设置语言环境
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2385474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set a locale in javascript
提问by ariel
jQuery tests the validity of a date via:
jQuery 通过以下方式测试日期的有效性:
!/Invalid|NaN/.test(new Date(value))
new Date(dateString)is the same as Date.parse(dateString)and uses browser/OS locale to parse the string.
new Date(dateString)与Date.parse(dateString)并使用浏览器/操作系统区域设置来解析字符串相同。
I'm trying to parse DD/MM/YYYYbut I get an error because my browser is looking for MM/DD/YYYY. Since my product will be used only by DD/MMpeople, I want to force this behaviour.
我正在尝试解析,DD/MM/YYYY但出现错误,因为我的浏览器正在寻找MM/DD/YYYY. 由于我的产品仅供DD/MM人们使用,因此我想强制执行此行为。
I could write a custom validator, but is it possible to change the browser locale via JavaScript as well?
我可以编写自定义验证器,但是否也可以通过 JavaScript 更改浏览器区域设置?
采纳答案by Sagi
You can't change the locale, as there is no such feature in the EMCAScript specification.
您不能更改区域设置,因为 EMCAScript规范中没有这样的功能。
However, there is a nice package called php.jsthat implements PHP functions in JavaScript.
然而,有一个很好的包叫做php.js,它在 JavaScript 中实现了 PHP 函数。
Two of the functions are setlocale() and date(). You can use them.
回答by Codebling
You should use moment.jsto parse dates.
您应该使用moment.js来解析日期。
//parse string according to format and return new moment
var day = moment("16/12/2017", "DD/MM/YYYY");
var dayAsDate = day.toDate(); //you can even covert the moment to a Date
Globalizealso has a date parsing moduleif you need to handle date strings in other locales/scripts.
回答by Jake H.
Use can now use JavaScript's Internationalization API because it's now supported in all browsers. It allows you to pass in a locale, which will customize the date format.
现在可以使用 JavaScript 的国际化 API,因为现在所有浏览器都支持它。它允许您传入语言环境,这将自定义日期格式。
console.log(new Intl.DateTimeFormat('en-GB').format(date));
console.log(new Intl.DateTimeFormat('en-GB').format(date));
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
参考:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
回答by Gipsy King
If your product will only be used by DD/MM/YYYY people, set your browser to a DD/MM/YYYY supporting locale.
如果您的产品仅供 DD/MM/YYYY 人使用,请将您的浏览器设置为支持 DD/MM/YYYY 的语言环境。

