Javascript 如何以 HH:MM:SS 格式比较两个时间字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6212305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:47:55  来源:igfitidea点击:

How can I compare two time strings in the format HH:MM:SS?

javascript

提问by Null Pointer

I have two time strings in HH:MM:SSformat. For example, str1contains 10:20:45, str2contains 5:10:10.

我有两个HH:MM:SS格式的时间字符串。例如,str1包含10:20:45str2包含5:10:10

How can I compare the above values?

如何比较上述值?

回答by Andy E

As Felix Klingsaid 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:SSyou can do a direct string comparison:

正如Felix Kling在评论中所说,如果您的时间基于 24 小时制(如果没有 AM/PM 则应该是),并且如果它们始终采用HH:MM:SS您可以进行直接字符串比较的格式:

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

回答by Evgeny Shadchnev

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.

1 月 1 日是一个任意日期,没有任何意义。

回答by Suresh Krishnamoorthi

Try this code for the 24 hrs format of time.

尝试使用此代码获取 24 小时格式的时间。

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

回答by hien

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

Datejs 中的对象支持比较,将它们设置为相同的日期进行比较 hh:mm:ss :

new Date ('1/1/1999 ' + '10:20:45') > new Date ('1/1/1999 ' + '5:10:10') 
> true

回答by Kishan Patel

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.

注意:RegExp 中的第二个参数是“g”,它是全局搜索标志。全局搜索标志使 RegExp 在整个字符串中搜索模式,创建一个数组,其中包含它可以找到的与给定模式匹配的所有匹配项。下面的代码仅适用于时间为 HH:MM:SS 格式即 24 小时时间格式的情况

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

回答by niksvp

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, "")) > parseInt(startTime .replace(regExp, ""))){
alert("End time is greater");
}

回答by patapizza

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

您可以在用 ':' 分割后立即比较这两个值。

回答by Ghasem Aladaghlou

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

我从@kamil-p 解决方案改进了这个功能。我忽略了 seconds compare 。您可以通过注意您的使用向此功能添加秒逻辑。

Work only for "HH:mm" time format.

仅适用于“HH:mm”时间格式。

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

感谢@kamil-p

回答by GameBoy

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>

回答by Sublime Laravel Dev

Best way to compare times using convert into ms

使用转换为毫秒来比较时间的最佳方法

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

return minutesOfDay(now) > minutesOfDay(end);