Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toLocaleDateString Javascript date format issues [duplicate]

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.

like image 497
mjcoder Avatar asked Jul 03 '13 23:07

mjcoder


People also ask

What date format is dd mm yyyy in JavaScript?

To format a date as dd/mm/yyyy:Use the getDate() , getMonth() and getFullYear() methods to get the day, month and year of the date. Add a leading zero to the day and month digits if the value is less than 10 .

Which method should be used to convert a date to a string in the current locale?

The format() method of DateFormat class is used to convert Date into String. DateFormat is an abstract class.


2 Answers

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.

like image 136
Koterpillar Avatar answered Sep 20 '22 20:09

Koterpillar


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('/');
}
like image 30
kennebec Avatar answered Sep 17 '22 20:09

kennebec