Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a locale in javascript

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?

like image 982
ariel Avatar asked Mar 05 '10 08:03

ariel


People also ask

What is locale in Javascript?

Locale (Runtime - JavaScript) A Locale object represents a specific geographical, political, or cultural region. An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user.

What is I18N Javascript?

Internationalization (I18N) is the process of designing and preparing software products (apps) to support multiple locales, languages, and regions. By internationalizing a codebase, developers and businesses can expand their user base and access a wider audience.

How does toLocaleString determine locale?

The toLocaleString method relies on the underlying operating system in formatting dates. It converts the date to a string using the formatting convention of the operating system where the script is running.


2 Answers

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

like image 132
Jake H. Avatar answered Oct 06 '22 00:10

Jake H.


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.

like image 20
Codebling Avatar answered Oct 05 '22 23:10

Codebling