比较if语句中的两个时间值

comparing two time values in an if statement

本文关键字:两个 时间 if 语句 比较      更新时间:2023-09-26

我需要比较两个值,并根据时间间隔是否超过1小时对比较结果进行处理。

例如

Time1 = 13:07:01    
Now = 13:26:47

我需要做的是在if语句中比较现在是否比时间1早一个小时,例如

If( Comparison){
  1 hour has passed
}else{
  1 hour has not passes 
}

最好的方法是什么?

使用Date() - MDN

if (Date.now() > new Date(oldDate) + 1000 * 60 * 60) {
    console.log('1 hour has passed');
} else {
    console.log('1 hour has not passed');
}
    <script>
        function checkForOneHr(){
              var start = '5:30';
              var end = '6:50';
              s = start.split(':');
              e = end.split(':');
              min = e[1]-s[1];
              hour_carry = 0;
              if(min < 0){
                  min += 60;
                  hour_carry += 1;
              }
              hour = e[0]-s[0]-hour_carry;
              if(hour >= 1)
               return true;
              else
               return false;
        } 
       if( checkForOneHr()){
           alert('1 hour has passed');
        }else{
          alert(' hour has not passes ');
         }

   </script>

如果是Date对象

var now = new Date();
var diff = now.getTime() - time1.getTime();
if(diff >= 1000*60*60) {
    console.log('an hour has passed');
} else {
    console.log('an hour has not passed');
}

首先,使用

将两个时间转换为字符串格式

strtotime () .

参见任何PHP手册。

把它们的差取出来

结果将在秒内不同。

将差值除以3600

如果大于1,执行"Code to do"。

。$current_time = date('T-m-d H:I:S');$time_now = strtotime($current_time);