Dates and time, eh? I hate them. Let's try to figure this out.
How you sort an array? With help of array's sort method. By default this method sorts strings, but we need custom compare function here.
How can we compare time in strings? We can use Date
object, parse time, get milliseconds from 1970, and compare them. But we have am-pm
format here. So, to use Date.parse
method, we need to convert time to 24 hour format first (or use Date.js library).
function convertTo24Hour(time) {
var hours = parseInt(time.substr(0, 2));
if(time.indexOf('am') != -1 && hours == 12) {
time = time.replace('12', '0');
}
if(time.indexOf('pm') != -1 && hours < 12) {
time = time.replace(hours, (hours + 12));
}
return time.replace(/(am|pm)/, '');
}
After we get 24h time, we can parse it like so (don't look at date before time, it doesn't matter, all we care about is time):
Date.parse( '9/19/2014 ' + convertTo24Hour(time) );
Now we can use this in array.sort
compare function. We just compare two numbers, 1411129800000 ? 1411132800000
, decide which one is bigger and sort array.
function compare(a,b) {
var atime = Date.parse('9/19/2014 ' + convertTo24Hour(a.time));
var btime = Date.parse('9/19/2014 ' + convertTo24Hour(b.time));
if (atime < btime) {
return -1;
}
if (atime > btime) {
return 1;
}
return 0;
}
What we got after all:
- Use
array.sort
compare function to sort elements
- Convert time to number so we can correctly compare them
- To do so, convert 12h time format to 24 and use
Date.parse
Here is jsfiddle to play with - http://jsfiddle.net/rqgmkdbs/