javascriptsortingdatedate-sorting

How to compare dates to see where adjacent times meet?


I have dates currently formatted in the following way:

[ [ Tue Jun 17 2014 09:00:00 GMT-0400 (EDT),
    Tue Jun 17 2014 10:00:00 GMT-0400 (EDT) ] ]

[ [ Thu Jun 19 2014 09:30:00 GMT-0400 (EDT),
    Thu Jun 19 2014 11:30:00 GMT-0400 (EDT) ] ]

[ [ Tue Jun 17 2014 10:00:00 GMT-0400 (EDT),
    Tue Jun 17 2014 11:00:00 GMT-0400 (EDT) ] ]

These dates are actually "sessions", and I need to see where certain sessions are adjacent to each other. For example, in this specific case, the first array of dates has a end time of 10AM while the last array of dates has a start time for 10AM. How can I computationally find this situation?

The one approach I have is to first sort the array sets from earliest time to to latest time, and then compare each of the start/end date pairs to see if they are the same, but I can't seem to get it through. Any ideas are welcome!


Solution

  • Turn the strings into Unix timestamps with Date.parse() (if these are actually Date objects, then use the .getTime() method) and then order the sessions with Array.prototype.sort(). Here's an example where the sessions are ordered by start time:

    var sessions = [
        ["Tue Jun 17 2014 09:00:00 GMT-0400 (EDT)", "Tue Jun 17 2014 10:00:00 GMT-0400 (EDT)"],
        ["Thu Jun 19 2014 09:30:00 GMT-0400 (EDT)", "Thu Jun 19 2014 11:30:00 GMT-0400 (EDT)"],
        ["Tue Jun 17 2014 10:00:00 GMT-0400 (EDT)", "Tue Jun 17 2014 11:00:00 GMT-0400 (EDT)"]
    ];
    
    for (var i = 0; i < sessions.length; i++) {
        sessions[i].startTime= Date.parse(sessions[i][0]);
    }
    
    sessions.sort(function(a, b) { return a.startTime-b.startTime; });