Rajneesh
Rajneesh

Reputation: 23

JavaScript date string sorting behaves differently on IE & Chrome

Below JavaScript line are executed differently on Chrome and IE.

var months =  ["Apr-2016", "Jun-2016", "Feb-2016", "Jan-2016",  "Mar-2016",  "May-2016", "Feb-2016", "Jun-2016", "Feb-2016", "Feb-2016", "Jan-2016"] ;
var uniqueMonths = months.filter( function (value, index, self) { return self.indexOf(value) === index;} );
uniqueMonths.sort(function(a,b){ return ((new Date(a).getTime()) - (new Date(b).getTime()));  });

On IE I get

uniqueMonths = ["Apr-2016", "Jun-2016", "Feb-2016", "Jan-2016", "Mar-2016", "May-2016"]

On chrome I get

uniqueMonths =  ["Jan-2016", "Feb-2016", "Mar-2016", "Apr-2016", "May-2016", "Jun-2016"] ;

What is reason for this beahaviour ?

Upvotes: 1

Views: 82

Answers (1)

meskobalazs
meskobalazs

Reputation: 16051

The date literals you have provided are invalid. It seems that Chrome parses it nevertheless. In this regard Firefox follows suit with IE, as it says:

new Date("Apr-2016")

Invalid Date

It is always preferable to use ISO dates, or if you don't, I'd recommend using a library, which provides a way to initialize JavaScript Date with specified format strings. Unfortunately native JavaScript lack this feature.

Upvotes: 2

Related Questions