Set a locale in javascript

2019-04-04 16:58发布

jQuery tests the validity of a date via:

!/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.

I'm trying to parse DD/MM/YYYY but I get an error because my browser is looking for MM/DD/YYYY. Since my product will be used only by DD/MM people, I want to force this behaviour.

I could write a custom validator, but is it possible to change the browser locale via JavaScript as well?

4条回答
爷、活的狠高调
2楼-- · 2019-04-04 17:04

If your product will only be used by DD/MM/YYYY people, set your browser to a DD/MM/YYYY supporting locale.

查看更多
时光不老,我们不散
3楼-- · 2019-04-04 17:06

You can't change the locale, as there is no such feature in the EMCAScript specification.

However, there is a nice package called php.js that implements PHP functions in JavaScript.

Two of the functions are setlocale() and date(). You can use them.

查看更多
可以哭但决不认输i
4楼-- · 2019-04-04 17:12

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.

console.log(new Intl.DateTimeFormat('en-GB').format(date));

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat

查看更多
做个烂人
5楼-- · 2019-04-04 17:16

You should use moment.js to parse dates.

//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

Globalize also has a date parsing module if you need to handle date strings in other locales/scripts.

查看更多
登录 后发表回答