Javascript sort not working in Firefox

Tags:



I have the following code which is sorting a list of javascript objects in an array based on their date. The data is coming from an XML file. The date is formatted as follows: MM-DD-YYYY

concert=new Object();
concert.performer=performerName;
concert.date=concertDate;
concerts[0]=concert; //adding to array in a for loop

So at this stage I have a load of concert objects in my concerts array. I then go to sort it and output it to a table:

sortedConcerts = concerts.sort(sortConcerts);

function sortConcerts(a, b){
var firstConcert=new Date(a.date);
var secondConcert=new Date(b.date);
return firstConcert-secondConcert;
}

I then have the new sorted array which I print out using a table or whatever.

My problem is that this works fine in IE and Chrome, but not in Firefox… what does Firefox not like?

Answer

Firefox seems to accept:

new Date("Jan 1 2009");
new Date("January 1 2009");
new Date("1 1 2009");
new Date("1/1/2009");

However using the hyphens gives you an invalid date format, which results in NaN for mathematic operations, (in your case, subtraction);

new Date("1/1/2009") - new Date("1-1-2009"); // NaN in Firefox, 0 in other browsers
new Date("1/1/2009") - new Date("1/1/2009"); // 0 in all browsers.

MDN has an article on valid date formats.



Source: stackoverflow