admin管理员组

文章数量:1129439

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?

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?

Share Improve this question edited Jun 2, 2011 at 8:48 Andy E 344k86 gold badges480 silver badges449 bronze badges asked Jun 2, 2011 at 8:46 Null PointerNull Pointer 9,28926 gold badges75 silver badges119 bronze badges 2
  • 1 possible duplicate of Compare time in javascript – lonesomeday Commented Jun 2, 2011 at 8:47
  • 17 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 Commented Jun 2, 2011 at 8:47
Add a comment  | 

18 Answers 18

Reset to default 211

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");
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.

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

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>

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');
}

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");
}

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...

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

Best way to compare times using convert into ms

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

return minutesOfDay(now) > minutesOfDay(end);

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>

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.');
 }

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

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;
}

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

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;
}

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

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;
        }
    }
}
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...
                }

本文标签: javascriptHow can I compare two time strings in the format HHMMSSStack Overflow