Javascript Sorting by date time

Im currently working on a web based calendar and I needed to sort my event object by date real quick. So the first thing I did was a quick search  on sorting an object by date time. Google becomes such second nature I immediately think of doing that first sometimes before fleshing out a whole solution in my mind. The first result I was brought to was this page on about.com. While the authors solution will work I thought why do even need this complexity? This is what I came up with when I stepped away from Google realizing this was a very trivial task

/*
* Function : sortDate(Date, Date)
* Description : Sorts an object based on date
*/
function sortDate(a,b)
{
    var a = new Date(a.startDateTime),
        b = new Date(b.startDateTime);
    return (a.getTime() - b.getTime());
}

My object has a property called startDateTime, but this can easily be modified. All I do is a quick comparison of the UNIX time stamp and its sorted. Mainly just hoping this eventually ranks higher than the result I found on Google.

3 thoughts on “Javascript Sorting by date time

  1. i read the data from the rows, at some row cells has multiple date’s. im reading these date and stored into an Array, after that i tried to Sort at that time im getting the error as “Microsoft JScript runtime error: Number expected”

    actually this is my sort method code

    function compareAscName(a, b)

    case ‘DOB’:
    var dateA = new Date(a.DOB);
    var dateB = new Date(b.DOB);
    return dateB – dateA;
    break;

    this is the code im calling above code

    dataInputArray.sort(compareAscName); when the system reach this code with multiple date in a array parameter then above method not called.

    if a = “09/07/2010~10/01/2010” and b= “09/08/2010~10/02/2010” then this time only im getting error,

    if a = “09/07/2010” and b= “09/08/2010” then this time its working fine. i knew some thing i have to do on

    case ‘DOB’:
    var dateA = new Date(a.DOB);
    var dateB = new Date(b.DOB);
    return dateB – dateA;
    break;

    this place but, i dont know how to do this?

  2. To return the years between 2 dates try

    var dob = new Date(“9/28/1982”),
    today = new Date(“9/21/2010”);

    alert(((today-dob)/86400000)/365);

    to return the days between 2 dates, just remove /365

  3. Pingback: JavaScript time between dates « Somethinghitme

Leave a Reply

Your email address will not be published. Required fields are marked *