2

What is the best wayto compare 2 'time' in 24 hour format in javascript?

I have converted the time to 24 hour format.

For eg:

t1, t2; //These are 2 time in 24 hour format of **string** type
        //Like t1="19:32" and t2 = "02:09"

if(t1<t2){} // Will this directly work for all times?

Any leads are appreciated.

user2696258
  • 1,159
  • 2
  • 14
  • 26

1 Answers1

1

One way you could do this, if the time is a string and always in the HH:MM 24 hour format, is parse the string and convert it into a number of minutes before performing the comparison. For example:

var time1 = "10:30";
var time2 = "12:30";

var time1InMinutesForTime1 = getTimeAsNumberOfMinutes(time1);
var time1InMinutesForTime2 = getTimeAsNumberOfMinutes(time2);

var time1IsBeforeTime2 = time1InMinutesForTime1 < time1InMinutesForTime2;

function getTimeAsNumberOfMinutes(time)
{
    var timeParts = time.split(":");

    var timeInMinutes = (timeParts[0] * 60) + timeParts[1];

    return timeInMinutes;
}

In this example, time1 will work out at 60,030 minutes and time2 will work out at 72,030 minutes, turning the comparison into a check between two numbers.

Rob
  • 45,296
  • 24
  • 122
  • 150
  • 1
    The times can be compared as strings. While converting to common units and comparing as numbers is a valid strategy, it's just not necessary. – RobG Jul 28 '17 at 01:50
  • 1
    @RobG, I agree completely, and I'd up-voted (though you couldn't see that! =) the comment by deceze that stated that. *However* I posted my answer as it makes it clearer what's being done and can be extended if someone who has a time in "HH:MM {AM|PM}" happens to come along, or if the HH isn't zero-padded; neither are requirements in the asked question, but if I can give an answer that satisfies both the OPs question and other cases, I like to do so =) – Rob Jul 28 '17 at 09:22