Skip to content Skip to sidebar Skip to footer

How To Sort Date Strings (format Example: 2014 7 23) In Javascript?

In JavaScript I'm trying to sort an array of objects, each having a date, by date, but I ran into an obstacle. Also the date's are input from 3 dropdown boxes on a site, so I just

Solution 1:

Looks like the date format is always the same as you're already splitting etc. and what you should do is use date objects and compare them instead

array.sort(function(a,b){
    var arr1 = a.date.split(" ");
    var arr2 = b.date.split(" ");

    var time1 = newDate(arr1[0], arr1[1]-1, arr1[2]); // year, month, dayvar time2 = newDate(arr2[0], arr2[1]-1, arr2[2]);

    return time1 - time2;
});

Solution 2:

DO use javascript's date object and do the following for sorting:

array.sort(function(a, b) {
    return a.date.getTime()-b.date.getTime();
});

Solution 3:

First off, lets just sort a few things out.

  • Javascript Date objects are stored as the number of milliseconds since datum, when you output them to a string they may well have milliseconds, timezone information etc but thats got nothing to do with their internals.
  • Your sort function is an overly complex way of just doing a.date - b.date

Therefore what you want to do is have the properties as actual Date objects, and use the sort function

var sortedArray = array.sort(function(a, b) {
  a.date - b.date;
});

Post a Comment for "How To Sort Date Strings (format Example: 2014 7 23) In Javascript?"