Reputation: 2394
I am not very good with manipulating strings and need some help.
I have this function which takes 2 divs and gets a paragraph that contains a string representing time in a format that looks like this:
Friday, 7 August 2015, 18:21 PM
or
Tuesday, 21 August 2015, 10:45 AM
as 2 examples. I want to create a sort comparator function which will return the correct number if one is larger than the other but I am not sure how to extract days when the number can be 1 or 2 digits long and also take into account the exact time etc..
The time string is the innerText part which I have split where there is a comma so that atime and btime are arrays for each section.
Here is what I have done so far:
// format: Friday, 7 August 2015, 18:21 PM
// atime[0] --> Friday
// atime[1] --> 7 August 2015
// atime[2] --> 18:21 PM
function sortByTimeAdded(a, b) {
var atime = (a.getElementsByClassName('timeAdded')[0].innerText).split(',');
var btime = (b.getElementsByClassName('timeAdded')[0].innerText).split(',');
/*if (atime[1] < btime[1]) {
return -1;
}
if (atime[1] > btime[1]) {
return 1;
}*/
return 0;
}
Thank you!
Upvotes: 0
Views: 2093
Reputation: 3725
I suggest using Date.parse, I will show on example:
var a = "Friday, 7 August 2015, 18:21 PM"
Date.parse(a.substring(0, a.length-3))
with this you get timestamp you can use for comparison.
If you need date object just replace Date.parse with Date()
Upvotes: 3