Set a locale in javascript
Solution 1
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.
Solution 2
You 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
Solution 3
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.
ariel
Updated on September 29, 2020Comments
-
ariel over 3 years
jQuery tests the validity of a date via:
!/Invalid|NaN/.test(new Date(value))
new Date(dateString)
is the same asDate.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 forMM/DD/YYYY
. Since my product will be used only byDD/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?
-
Pointy about 14 yearsWow, I would never ever recommend that anybody touch that php.js code with a pole of arbitrary length. Yuk.
-
Sagi about 14 yearsHe can always watch the dependencies and use only the necessary functions.
-
ariel about 14 yearsim not using the php.js, accepted for the information that its impossible to change locale in javascript
-
ELLIOTTCABLE almost 14 yearsWow. Suggesting, not only that he utilize a huge library for this single purpose… but suggesting, specifically, a library that emulates *PHP*‽ That’s… irresponsible, to say the least. -1’d.
-
Sagi over 12 yearsWell, if you have any other idea, you are welcome to post it. Otherwise, he can use the specified functions from php.js. No need to use the whole library of course.
-
George about 5 years"impossible" proceeds to link to javascript library stating it is possible