0

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!

4
  • So you want them sorted chronologically? Commented Aug 6, 2015 at 13:57
  • yes I do, just not sure how and also how to make it efficient. Commented Aug 6, 2015 at 13:59
  • 2
    innerText is not standard and unsupported by Firefox. Better use textContent. Commented Aug 6, 2015 at 14:00
  • Thanks! I had no idea. I better change some of my old code then :S Commented Aug 6, 2015 at 14:02

1 Answer 1

3

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()

Sign up to request clarification or add additional context in comments.

7 Comments

That definitely helps me to get started. Thanks for the tip!
Alternately, if you do new Date() on your date string you get a nice js date object. Call getTime() on it and you get the unix milliseconds. Use that for direct int comparison.
That's actually perfect. I didn't realize it converts all text to numbers, much more efficient then anything I could have done. Thank you again.
Try without the PM at the end
I mean, the date really is badly formatted, you should not have both 24 hour format and PM. It's either the one or the other.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.