使用php检查给定时间减去现在的时间是否少于60分钟

时间:2018-11-24 20:55:56

标签: php datetime time

我在这里已经阅读了很多,并且尝试了很多,但是我没有明白:(

我有:

$end = new DateTime('22:00');
$now = new DateTime();

if(($end - $now) < 60)
{
    $bijnaTijd = "bijnaTijdJa";
}

我想看看$end与当前时间之间的时差是否少于60分钟。有人可以帮我吗?

2 个答案:

答案 0 :(得分:0)

请检查此代码,希望它可以解决您的问题

<?php 
$end        = new DateTime('22:00');
$new_end    = strtotime($end->format('Hi')); //convert to string
$end_h      = idate('h', $new_end); //get the hour
$end_h      = str_pad($end_h, 2, 0, STR_PAD_RIGHT);
$end_m      = idate('i', $new_end);
$end_m      = str_pad($end_m, 2, 0, STR_PAD_LEFT); //get leading zero for above minutes 10
$time_end   = $end_h.''.$end_m;

$now = new DateTime();
$new_now    = strtotime($now->format('Hi'));
$now_h      = idate('h', $new_now);
$now_h      = str_pad($now_h, 2, 0, STR_PAD_RIGHT);
$now_m      = idate('i', $new_now);
$now_m      = str_pad($now_m, 2, 0, STR_PAD_LEFT);
$time_now   = $now_h.''.$now_m;


echo ($time_end - $time_now); //get the result do your logic after this code

答案 1 :(得分:0)

您需要使用getTimestamp()DateTime对象获取时间戳,并相互比较时间戳。

请注意,时间戳以秒为单位,所以我使用60*60将分钟转换为秒。

$end = new DateTime('22:00');
$now = new DateTime();

if (($end->getTimestamp() - $now->getTimestamp()) < 60*60){
    // do something
}

您还可以使用日期函数代替DateTime类。

if (strtotime('22:00') - time() < 60*60){
    // do something
}
相关问题