0

I want to check if a time is earlier than another time using JavaScript or any JavaScript library.

For example I have t1=12:45:30 and t2=12:45:35 I want to check if t1 is earlier than t2. How can I easily do it using JavaScript?

I was trying the following code:

if(t1<t2)

But it is not working.

Terry
  • 989
  • 8
  • 29
  • possible duplicate http://stackoverflow.com/questions/492994/compare-two-dates-with-javascript –  May 12 '15 at 16:42
  • `t1=12:45:30` is not valid JavaScript. How are you *actually* creating your dates? – p.s.w.g May 12 '15 at 16:42
  • yes it's not a valid Js date,one approach would be to split the your date in an array and den compare.. – Ritt May 12 '15 at 16:47
  • If the t1 is string, first split it with arr = t1.split(":") and then multiply the values with parseInt( arr[0] )*60*60 + parseInt( arr[1] )*60 + parseInt( arr[2] ) – Tero Tolonen May 12 '15 at 16:47
  • is there no built in function in d3.time? –  May 12 '15 at 16:52

2 Answers2

1

As others have pointed out, "12:34:42" is not a valid javascript timestamp which precludes you from using the Date object, but you could easily convert the time string into seconds and compare those values:

var seconds = function(time) {
  return time.split(":").reverse().reduce(function(p,c,i) { 
    return p + (parseInt(c, 10) * (Math.pow(60, i)));
  }, 0);
}

if(seconds(t1) < seconds(t2)) {
  ... do stuff
}

Or if you have ES6 available:

const seconds = (time) => time.split(":").reverse().reduce((p,c,i) => {
    return p + (parseInt(c, 10) * (Math.pow(60, i)));
}, 0);
Rob M.
  • 35,491
  • 6
  • 51
  • 50
1

If you are using 24 hour time you can remove the colons and subtract the digits to compare two times.

A negative return indicates the first argument is less than the second.

Positive means the first is greater, and zero means they are identical.

function compareHMS(hms1, hms2){
    return hms1.replace(/\D+/g,'')-hms2.replace(/\D+/g,''); 
}

compareHMS('12:45:30', '12:45:35');

// returned value: (Number) -5

kennebec
  • 102,654
  • 32
  • 106
  • 127