13

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.

Aleks G
  • 56,435
  • 29
  • 168
  • 265
  • I use _Chrome_, my _Windows_ machine region is set to _UK/England/London_, `toLocaleDateString` gives me US style dates. I think it's because we speak _English_ so just download the default _en-US_ version of the browser. I usually write dates in an international way which is unmistakable, for example `2014-02-05` for today. – Paul S. Feb 05 '14 at 22:00
  • What does `(new Date()).toLocaleDateString()` give? – JayInNyc Feb 05 '14 at 22:01
  • I'm also having this issue, On two machines in our office one returns `toLocaleDateString` the US way the other the UK way. I tried `toLocaleDateString(window.navigator.language)`. But it just flips the problem as on the one returning the UK date it returns its language as "en-US" which makes no sense!! what is it based on? – znap026 Sep 04 '18 at 09:56

2 Answers2

6

Use this to pass the locale.

var locale = window.navigator.userLanguage || window.navigator.language;
alert(date.toLocaleString(locale));
JJJ
  • 32,902
  • 20
  • 89
  • 102
Jas
  • 71
  • 1
  • 1
4

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/

Tilman Schweitzer
  • 1,437
  • 10
  • 10
  • 5
    This defeats the purpose. I don't know what the locale is - I want the to automatically match user's locale. – Aleks G Feb 05 '14 at 22:18
  • You said your computers locale is UK/GB but your browsers is probably not. It's also possible that JavaScripts hat no possibility to get you locale further than the language, as this post suggests. http://stackoverflow.com/questions/673905/best-way-to-determine-users-locale-within-browser – Tilman Schweitzer Feb 05 '14 at 22:25