检查JavaScript中的时间是否早于其他时间

时间:2022-03-28 20:14:36

I want to check if a time is earlier than another time using JavaScript or any JavaScript library.

我想检查时间是否早于使用JavaScript或任何JavaScript库的另一次。

For example I have t1=12:45:30 and t2=12:45:35 I want to check if t1 is earlier than t2. How can I easily do it using JavaScript?

例如,我有t1 = 12:45:30和t2 = 12:45:35我想检查t1是否早于t2。如何使用JavaScript轻松完成?

I was trying the following code:

我正在尝试以下代码:

if(t1<t2)

But it is not working.

但它没有用。

2 个解决方案

#1


As others have pointed out, "12:34:42" is not a valid javascript timestamp which precludes you from using the Date object, but you could easily convert the time string into seconds and compare those values:

正如其他人所指出的那样,“12:34:42”不是一个有效的javascript时间戳,它阻止你使用Date对象,但你可以轻松地将时间字符串转换为秒并比较这些值:

var seconds = function(time) {
  return time.split(":").reverse().reduce(function(p,c,i) { 
    return p + (parseInt(c, 10) * (Math.pow(60, i)));
  }, 0);
}

if(seconds(t1) < seconds(t2)) {
  ... do stuff
}

Or if you have ES6 available:

或者,如果您有ES6可用:

const seconds = (time) => time.split(":").reverse().reduce((p,c,i) => {
    return p + (parseInt(c, 10) * (Math.pow(60, i)));
}, 0);

#2


If you are using 24 hour time you can remove the colons and subtract the digits to compare two times.

如果您使用24小时时间,则可以删除冒号并减去数字以进行两次比较。

A negative return indicates the first argument is less than the second.

否定回报表示第一个参数小于第二个参数。

Positive means the first is greater, and zero means they are identical.

正数表示第一个更大,零表示它们相同。

function compareHMS(hms1, hms2){
    return hms1.replace(/\D+/g,'')-hms2.replace(/\D+/g,''); 
}

compareHMS('12:45:30', '12:45:35');

// returned value: (Number) -5

//返回值:(Number)-5

#1


As others have pointed out, "12:34:42" is not a valid javascript timestamp which precludes you from using the Date object, but you could easily convert the time string into seconds and compare those values:

正如其他人所指出的那样,“12:34:42”不是一个有效的javascript时间戳,它阻止你使用Date对象,但你可以轻松地将时间字符串转换为秒并比较这些值:

var seconds = function(time) {
  return time.split(":").reverse().reduce(function(p,c,i) { 
    return p + (parseInt(c, 10) * (Math.pow(60, i)));
  }, 0);
}

if(seconds(t1) < seconds(t2)) {
  ... do stuff
}

Or if you have ES6 available:

或者,如果您有ES6可用:

const seconds = (time) => time.split(":").reverse().reduce((p,c,i) => {
    return p + (parseInt(c, 10) * (Math.pow(60, i)));
}, 0);

#2


If you are using 24 hour time you can remove the colons and subtract the digits to compare two times.

如果您使用24小时时间,则可以删除冒号并减去数字以进行两次比较。

A negative return indicates the first argument is less than the second.

否定回报表示第一个参数小于第二个参数。

Positive means the first is greater, and zero means they are identical.

正数表示第一个更大,零表示它们相同。

function compareHMS(hms1, hms2){
    return hms1.replace(/\D+/g,'')-hms2.replace(/\D+/g,''); 
}

compareHMS('12:45:30', '12:45:35');

// returned value: (Number) -5

//返回值:(Number)-5