Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript users incorrect locale with date formatting

In javascript I'm using Date.toLocaleDateString to format my dates in the user's locale. While in theory it should work, it doesn't.

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

The full code for formatting is this:

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

In the UK for today's date I would expect to see 05/02/2014, but I see 02/05/2014, which is the US version of it.

like image 650
Aleks G Avatar asked Feb 05 '14 21:02

Aleks G


2 Answers

Use this to pass the locale.

var locale = window.navigator.userLanguage || window.navigator.language;
alert(date.toLocaleString(locale));
like image 193
Jas Avatar answered Nov 02 '22 22:11

Jas


A quick look into to awesome MDN Documentation tells me that you need a locale parameter, otherwise the result depends on the browser. 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 custom date formats I use the moment.js library. http://momentjs.com/

like image 29
Tilman Schweitzer Avatar answered Nov 03 '22 00:11

Tilman Schweitzer