This question already has answers here:
Compare two dates with JavaScript
                            
                                (38个答案)
                            
                    
                    
                        Compare two time (hh:mm:ss) strings
                            
                                (5个答案)
                            
                    
                2年前关闭。
        

    

在JavaScript中以24小时格式比较2个“时间”的最佳方法是什么?

我已将时间转换为24小时格式。

例如:

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?


任何线索表示赞赏。

最佳答案

如果时间是字符串,并且始终采用HH:MM 24小时格式,则可以执行此操作的一种方法是解析字符串并将其转换为分钟数,然后再执行比较。例如:

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


在此示例中,time1将在60,030分钟处计算,而time2将在72,030分钟处计算,从而将比较结果转换为两个数字之间的校验。

10-05 20:19