PHP检查当前时间是否在指定时间之前

时间:2011-12-12 13:23:33

标签: php date strtotime

我需要在PHP中检查当前时间是否在当天下午2点之前。

我在之前的日期使用strtotime完成了此操作,但这次只有时间,所以显然每天重置时间为0.00,布尔值将从false重置为true

if (current_time < 2pm) {
   // do this
}

9 个答案:

答案 0 :(得分:68)

if (date('H') < 14) {
   $pre2pm = true;
}

有关日期功能的更多信息,请see the PHP manual。我使用了以下时间格式器:

  

H = 24小时格式的一小时(00到23)

答案 1 :(得分:23)

尝试:

if(date("Hi") < "1400") {
}

请参阅:http://php.net/manual/en/function.date.php

H   24-hour format of an hour with leading zeros    00 through 23
i   Minutes with leading zeros                      00 to 59

答案 2 :(得分:13)

你可以传递时间

if (time() < strtotime('2 pm')) {
   //not yet 2 pm
}

或明确传递日期

if (time() < strtotime('2 pm ' . date('d-m-Y'))) {
   //not yet 2 pm
}

答案 3 :(得分:4)

使用24小时的时间解决问题:

$time = 1400;
$current_time = (int) date('Hi');
if($current_time < $time) {
    // do stuff
}

因此,2PM相当于24小时内的14:00。如果我们从那时起删除冒号,那么我们可以在比较中将其评估为整数。

有关日期功能的更多信息,请see the PHP manual。我使用了以下格式化程序:

  

H = 24小时格式的一小时(00到23)

     

i =前导零(00到59)的分钟

答案 4 :(得分:1)

你还没有告诉我们你正在运行哪个版本的PHP,但假设它是PHP 5.2.2+而不是你应该这样做:

$now = new DateTime();
$twoPm = new DateTime();
$twoPm->setTime(14,0); // 2:00 PM

然后问:

if ( $now < $twoPm ){ // such comparison exists in PHP >= 5.2.2
    // do this
}

否则,如果你使用旧版本之一(比如5.0),这应该可以解决问题(并且更加简单):

$now = time();
$twoPm = mktime(14); // first argument is HOUR

if ( $now < $twoPm ){
    // do this
}

答案 5 :(得分:1)

如果您想检查时间是否在下午2:30之前,您可以尝试以下代码段。

if (date('H') < 14.30) {
   $pre2pm = true;   
}else{
   $pre2pm = false;
}

答案 6 :(得分:0)

尝试

if( time() < mktime(14, 0, 0, date("n"), date("j"), date("Y")) ) {

// do this

}

答案 7 :(得分:0)

此功能将通过接受2个参数,带有小时和上午/下午的数组来检查它是否在美国东部时间的小时数之间...

    /**
     * Check if between hours array(12,'pm'), array(2,'pm')
     */
    function is_between_hours($h1 = array(), $h2 = array())
    {
        date_default_timezone_set('US/Eastern');
        $est_hour = date('H');

        $h1 = ($h1[1] == 'am') ? $h1[0] : $h1[0]+12;
        $h1 = ($h1 === 24) ? 12 : $h1;

        $h2 = ($h2[1] == 'am') ? $h2[0] : $h2[0]+12;
        $h2 = ($h2 === 24) ? 12 : $h2;

        if ( $est_hour >= $h1 && $est_hour <= ($h2-1) )
            return true;

        return false;
    }

答案 8 :(得分:0)

使用time()date()strtotime()函数:

if(time() > strtotime(date('Y-m-d').' 14:00') {
    //...
}
相关问题