117

I have two time strings in HH:MM:SS format. For example, str1 contains 10:20:45, str2 contains 5:10:10.

How can I compare the above values?

Andy E
  • 338,112
  • 86
  • 474
  • 445
Null Pointer
  • 9,089
  • 26
  • 73
  • 118
  • 1
    possible duplicate of [Compare time in javascript](http://stackoverflow.com/questions/3316281/compare-time-in-javascript) – lonesomeday Jun 02 '11 at 08:47
  • 16
    Is it 24h? Then you can do simple string comparison. Btw, `5:10:10` is not `HH:MM...` it is only `H:MM:...`. But for string comparison both really have to be in the same format. – Felix Kling Jun 02 '11 at 08:47

18 Answers18

202

As Felix Kling said in the comments, provided your times are based on a 24 hour clock (and they should be if there's no AM/PM) and provided they are always in the format HH:MM:SS you can do a direct string comparison:

var str1 = "10:20:45",
    str2 = "05:10:10";

if (str1 > str2)
    alert("Time 1 is later than time 2");
else
    alert("Time 2 is later than time 1");
Andy E
  • 338,112
  • 86
  • 474
  • 445
  • This is dependent on using ASCII for representation since the codes are conveniently in order –  Mar 25 '13 at 20:12
  • with this method if i compare string `str1 = "00:10"` with `str2 = "01:10"` and check that if string 1 is greater then string 2 alert string string one is greater else alert string 2 is greater i think 12PM is grater than 1AM but it shows string 2 is greater – Mubeen Ali Aug 02 '13 at 19:43
  • 3
    @Mubeen1992: that's why my answer says this requires that the times are based on the 24-hour clock. You have to use a different method for your scenario. – Andy E Aug 03 '13 at 09:48
  • i didn't get your mean. I am also comparing two strings that uses 24 hour clock. `str1` is 12:10pm and `str2` is 1:10am – Mubeen Ali Aug 03 '13 at 12:36
  • 2
    @Mubeen1992: `1:10am` is irregular as a 24-hour time format. `01:10` would be more correct and `01:10` would compare properly to `12:10`. Like I said, for your strings, you need to use a different method. – Andy E Aug 09 '13 at 15:56
  • 1
    This is brilliant, I love the simplicity. Every other method I found forced me to impose (implicitly or explicitly) a date on top of the time, but I _only_ care about time, so this is perfect. – jon_simon Aug 16 '17 at 04:37
  • What if, I compare `var str1 = "10:65", str2 = " 10:55";` ? – Rahul Bali Sep 22 '18 at 04:53
  • @RahulBali Why not convert 10:65 to 11:05? That's what I do in my case. – Christophe Geers Apr 21 '19 at 09:44
  • @Andy E great answer man no need to convert in a date like stuff awesome :-) – Rabby Oct 05 '20 at 09:54
  • Why does this work? Does JavaScript recognize the format and convert the strings to date objects for comparision internally? – Ansh Saini Apr 30 '21 at 12:48
145
Date.parse('01/01/2011 10:20:45') > Date.parse('01/01/2011 5:10:10')
> true

The 1st January is an arbitrary date, doesn't mean anything.

Evgeny Shadchnev
  • 7,320
  • 4
  • 27
  • 30
  • 15
    **Note**: Parsing of strings with `Date.parse` is strongly discouraged due to browser differences and inconsistencies. [MDN](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date#Methods) – Zev Isert Jan 31 '17 at 00:22
9

Date object in js support comparison, set them same date for compare hh:mm:ss :

new Date ('1/1/1999 ' + '10:20:45') > new Date ('1/1/1999 ' + '5:10:10') 
> true
hien
  • 1,988
  • 2
  • 17
  • 13
6

Try this code for the 24 hrs format of time.

<script type="text/javascript">
var a="12:23:35";
var b="15:32:12";
var aa1=a.split(":");
var aa2=b.split(":");

var d1=new Date(parseInt("2001",10),(parseInt("01",10))-1,parseInt("01",10),parseInt(aa1[0],10),parseInt(aa1[1],10),parseInt(aa1[2],10));
var d2=new Date(parseInt("2001",10),(parseInt("01",10))-1,parseInt("01",10),parseInt(aa2[0],10),parseInt(aa2[1],10),parseInt(aa2[2],10));
var dd1=d1.valueOf();
var dd2=d2.valueOf();

if(dd1<dd2)
{alert("b is greater");}
else alert("a is greater");
}
</script>
6

You can easily do it with below code:

Note: The second argument in RegExp is 'g' which is the global search flag. The global search flag makes the RegExp search for a pattern throughout the string, creating an array of all occurrences it can find matching the given pattern. Below code only works if the time is in HH:MM:SS format i.e. 24 hour time format.

var regex = new RegExp(':', 'g'),
    timeStr1 = '5:50:55',
    timeStr2 = '6:17:05';
if(parseInt(timeStr1.replace(regex, ''), 10) < parseInt(timeStr2.replace(regex, ''), 10)){
  console.log('timeStr1 is smaller then timeStr2');
} else {
  console.log('timeStr2 is smaller then timeStr1');
}
Kishan Patel
  • 509
  • 7
  • 16
5

Convert to seconds those strings:

var str1 = '10:20:45';
var str2 = '5:10:10';

str1 =  str1.split(':');
str2 =  str2.split(':');

totalSeconds1 = parseInt(str1[0] * 3600 + str1[1] * 60 + str1[2]);
totalSeconds2 = parseInt(str2[0] * 3600 + str2[1] * 60 + str2[2]);

// compare them

if (totalSeconds1 > totalSeconds2 ) { // etc...
pmiranda
  • 7,602
  • 14
  • 72
  • 155
  • 1
    I think you meant `totalSeconds1 = parseInt(str1[0] * 3600 + str1[1] * 60 + str1[2]); totalSeconds2 = parseInt(str2[0] * 3600 + str2[1] * 60 + str2[2]);` – ruttergod May 17 '23 at 20:44
4

Try this code.

var startTime = "05:01:20";
var endTime = "09:00:00";
var regExp = /(\d{1,2})\:(\d{1,2})\:(\d{1,2})/;
if(parseInt(endTime .replace(regExp, "$1$2$3")) > parseInt(startTime .replace(regExp, "$1$2$3"))){
alert("End time is greater");
}
niksvp
  • 5,545
  • 2
  • 24
  • 41
2

I improved this function from @kamil-p solution. I ignored seconds compare . You can add seconds logic to this function by attention your using.

Work only for "HH:mm" time format.

function compareTime(str1, str2){
    if(str1 === str2){
        return 0;
    }
    var time1 = str1.split(':');
    var time2 = str2.split(':');
    if(eval(time1[0]) > eval(time2[0])){
        return 1;
    } else if(eval(time1[0]) == eval(time2[0]) && eval(time1[1]) > eval(time2[1])) {
        return 1;
    } else {
        return -1;
    }
}

example

alert(compareTime('8:30','11:20'));

Thanks to @kamil-p

Aladaghlou
  • 83
  • 5
2

Best way to compare times using convert into ms

var minutesOfDay = function(m){
      return m.minutes() + m.hours() * 60;
    }

return minutesOfDay(now) > minutesOfDay(end);
  • 1
    Note that there is already an accepted answer to this question. Please [edit] your answer to ensure that it improves upon other answers already present in this question. – hongsy Jan 28 '20 at 09:00
1

I think you can put it like this.

var a = "10:20:45";
var b = "5:10:10";

var timeA = new Date();
timeA.setHours(a.split(":")[0],a.split(":")[1],a.split(":")[2]);
timeB = new Date();
timeB.setHours(b.split(":")[0],b.split(":")[1],b.split(":")[2]);

var x= "B is later than A";
if(timeA>timeB) x = "A is later than B";
document.getElementById("demo").innerHTML = x;
<p id="demo"></p>
GameBoy
  • 111
  • 7
1

Set the extracted part of the time to variables.

// If you don't have the second part then set it to 00.

 //Create date object and set the time to that
 var startTimeObject = new Date();
 startTimeObject.setHours(startHour, startMinute, startSecond);

 //Create date object and set the time to that
 var endTimeObject = new Date(startTimeObject);
 endTimeObject.setHours(endHour, endMinute, endSecond);

 //Now we are ready to compare both the dates
 if(startTimeObject > endTimeObject) {
     alert('End time should be after start time.');
 }
 else {
     alert('Entries are perfect.');
 }
Irshad Khan
  • 5,670
  • 2
  • 44
  • 39
1

time format should be in HH:mm:ss HH for 24 hour format

if (start_time > end_time)
    console.log('start time is greater than end time')
else console.log('end time is greater than start time')
0

I'm not so comfortable with regular expressions, and my example results from a datetimepicker field formatted m/d/Y h:mA. In this legal example, you have to arrive before the actual deposition hearing. I use replace function to clean up the dates so that I can process them as Date objects and compare them.

function compareDateTimes() {
    //date format ex "04/20/2017 01:30PM"
    //the problem is that this format results in Invalid Date
    //var d0 = new Date("04/20/2017 01:30PM"); => Invalid Date

    var start_date = $(".letter #depo_arrival_time").val();
    var end_date = $(".letter #depo_dateandtime").val();

    if (start_date=="" || end_date=="") {
        return;
    }
    //break it up for processing
    var d1 = stringToDate(start_date);
    var d2 = stringToDate(end_date);

    var diff = d2.getTime() - d1.getTime();
    if (diff < 0) {
        end_date = moment(d2).format("MM/DD/YYYY hh:mA");
        $(".letter #depo_arrival_time").val(end_date);
    }
}

function stringToDate(the_date) {
    var arrDate = the_date.split(" ");
    var the_date = arrDate[0];
    var the_time = arrDate[1];
    var arrTime = the_time.split(":");
    var blnPM = (arrTime[1].indexOf("PM") > -1);
    //first fix the hour
    if (blnPM) {
        if (arrTime[0].indexOf("0")==0) {
            var clean_hour = arrTime[0].substr(1,1);
            arrTime[0] = Number(clean_hour) + 12;
        }
        arrTime[1] = arrTime[1].replace("PM", ":00");
    } else {
        arrTime[1] = arrTime[1].replace("AM", ":00");
    }
    var date_object =  new Date(the_date);
    //now replace the time
    date_object = String(date_object).replace("00:00:00", arrTime.join(":"));
    date_object =  new Date(date_object);

    return date_object;
}
Nicolas Giszpenc
  • 677
  • 6
  • 11
0

You could compare the two values right after splitting them with ':'.

patapizza
  • 2,398
  • 15
  • 14
0

Improved and more comfortable version on Evgeny Shadchnev's answer:

/**
 * Correctly compares values like time1 === '02', time2 === '12:12:34'.
 * Correctrly compares even '1:02', '01:2' and similar values.
 *
 * @param time1 String  for example 02 (2 hours), 02:03 (two hours, three minutes), 02:03:02 (two hours, three minutes, two seconds)
 * @param time2 String  look for time1 description
 * @returns {number} 1 if time1 > time2, -1 if time1 < time2, 0 if time1 === time2
*/
let compareStringTimes = function(time1, time2){
  // 01/01/2011 is an arbitrary date, doesn't mean anything..
  let date1 = Date.parse(`01/01/2011 ${time1}`)
  let date2 = Date.parse(`01/01/2011 ${time2}`)
  return date1 > date2 ? 1 : date1 < date2 ? -1 : 0;
}
FlamyTwista
  • 447
  • 5
  • 17
0

I had to compare 2 time string, if the current time lies within these 2 time frame then button will be enable otherwise disable . This logic will also work if the start time 10:00 pm and end time is 02:00 am (which is next day).

   const date = new Date();
    const currentHour = date.getHours();
    const currentMinute = date.getMinutes();
const startTime="20:00:00"
const endTime="2:00:00"
    const str1 = startTime.split(":");
    const str2 = endTime.split(":");
    let currentTotal = currentHour * 3600 + currentMinute * 60;
    const startTimeTotal = parseInt(str1[0] * 3600 + str1[1] * 60);
    let endTimeTotal = parseInt(str2[0] * 3600 + str2[1] * 60);

    if (startTimeTotal <= endTimeTotal) {
      // If the end time is on the same day
      if (currentTotal >= startTimeTotal && currentTotal <= endTimeTotal) {
        console.log("disable button",true);
      } else {
              console.log("disable button",false)
      }
    } else {
      // If the end time is on the next day
      if (currentTotal >= startTimeTotal || currentTotal <= endTimeTotal) {
        console.log("disable button",true)
      } else {
              console.log("disable button",false)
      }
    }
-1
var str1 = "150:05:05",
var str2 = "80:04:59";   

function compareTime(str1, str2){

    if(str1 === str2){
        return 0;
    }

    var time1 = str1.split(':');
    var time2 = str2.split(':');

    for (var i = 0; i < time1.length; i++) {
        if(time1[i] > time2[i]){
            return 1;
        } else if(time1[i] < time2[i]) {
            return -1;
        }
    }
}
Kamil P.
  • 11
  • 2
-3
var startTime = getTime(document.getElementById('startTime').value);
                var endTime = getTime(document.getElementById('endTime').value);


                var sts = startTime.split(":");
                var ets = endTime.split(":");

                var stMin = (parseInt(sts[0]) * 60 + parseInt(sts[1]));
                var etMin = (parseInt(ets[0]) * 60 + parseInt(ets[1]));
                if( etMin > stMin) {
                // do your stuff...
                }
JGeo
  • 380
  • 13
  • 33
  • Does not work. Format is "12:34:56". This is treating the hours as minutes, the minutes as seconds, and it ignores the seconds: var stMin = (parseInt(sts[0]) * 60 + parseInt(sts[1])); – HoldOffHunger Sep 14 '17 at 19:14