7

I've got a script and i want to format a date out to short date format ie:

7/3/2013 or 7/3/13 the first date format renders like that in Chrome but every other browser it does not - it displays the date month name and the year.

function dateFormatter(date) {
  return date.toLocaleDateString();
}

Bit confused as to why this is happening. Is it because that browser doesnt support tolocalDateString();

Would i need to build a custom date string in order for it to work?

Sorry if its a little vague - I've had a look on W3C website but dont trust that site at times.

mjcoder
  • 1,009
  • 9
  • 25
  • 45

2 Answers2

10

The default format of toLocaleDateString is implementation-defined. If you want precise control of what's displayed, use a browser supporting locales and options arguments to toLocaleDateString. Unfortunately, at the moment that means only Chrome.

If you don't care about the user and their locale and would like to confuse everyone with US date format, then yes, you can hardcode the date parts as @kennebec suggested.

Koterpillar
  • 7,883
  • 2
  • 25
  • 41
4
function dateFormatter(date){
    if(Date.parse('2/6/2009')=== 1233896400000){
        return [date.getMonth()+1, date.getDate(), date.getFullYear()].join('/');
    }
    return [date.getDate(), date.getMonth()+1, date.getFullYear()].join('/');
}
kennebec
  • 102,654
  • 32
  • 106
  • 127
  • 8
    This is not locale-aware at all... – Koterpillar Jul 04 '13 at 00:39
  • @kennebec that worked perfectly. I tried something similar to this but to be honest i just messed it up. But yes that worked smoothly. Cheers. – mjcoder Jul 04 '13 at 08:23
  • 1
    @kennebec, what is with the if condition doing, why do we need this weird 2/6/2009 date check? – Nathan Tregillus May 21 '15 at 22:06
  • It's a locale thing... some places the month is first, and in others it is second... so this actually is totally locale-aware – Serj Sagan Oct 08 '15 at 23:46
  • 2
    @SerjSagan: This answer is not locale-aware in three respects: (a) the behavior of `Date.parse()` with strings other than in the [ISO 8601-based format](http://www.ecma-international.org/ecma-262/6.0/#sec-date-time-string-format) is [implementation-defined](http://www.ecma-international.org/ecma-262/6.0/#sec-date.parse). (b) the output uses fixed separator `/`, and (c) locales whose short date format places the _year_ first are not taken into account. – mklement0 May 24 '16 at 05:04