Incorrect date formatting Javascript locale

In javascript, I use Date.toLocaleDateStringto format my dates in a user locale. Although theoretically this should work, it is not.

I am in the UK. My computer is configured for the UK, and my default language is set to en / gb both in the system settings and in the browser content settings. However, Firefox always displays dates in US format. Is there any trick I'm missing?

The full formatting code is:

var timestamp = ...; //some value from ajax call
var dt = new Date(timestamp);
$('#audit-date').text(dt.toLocaleDateString());

In the UK today I expect to see 05/02/2014, but I see 02/05/2014, which is the American version.

+4
source share
2 answers

A quick look at the wonderful MDN documentation tells me that you need the locale parameter, otherwise the result is browser dependent. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

// British English uses day-month-year order
alert(date.toLocaleString("en-GB"));
// → "20/12/2012 03:00:00"

For more personalized date formats, I use the moment.js library. http://momentjs.com/

+2
source

Use this to pass the locale.

var locale = window.navigator.userLanguage || window.navigator.language;
alert(date.toLocaleString(locale));
0
source

Source: https://habr.com/ru/post/1525516/


All Articles