PHP Check if current time is before specified time

前端 未结 9 2046
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-29 01:51

I need to check in PHP if the current time is before 2pm that day.

I\'ve done this with strtotime on dates before, however this time it\'s with a time o

相关标签:
9条回答
  • 2020-12-29 02:30

    Try:

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

    See: 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
    
    0 讨论(0)
  • 2020-12-29 02:30

    You haven't told us which version of PHP you're running, although, assuming it's PHP 5.2.2+ than you should be able do it like:

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

    then just ask:

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

    otherwise, if you're using one of older version (say, 5.0) this should do the trick (and is much simplier):

    $now = time();
    $twoPm = mktime(14); // first argument is HOUR
    
    if ( $now < $twoPm ){
        // do this
    }
    
    0 讨论(0)
  • 2020-12-29 02:31

    Try with

    if( time() < mktime(14, 0, 0, date("n"), date("j"), date("Y")) ) {
    
    // do this
    
    }
    
    0 讨论(0)
  • 2020-12-29 02:38
    if (date('H') < 14) {
       $pre2pm = true;
    }
    

    For more information about the date function please see the PHP manual. I have used the following time formatter:

    H = 24-hour format of an hour (00 to 23)

    0 讨论(0)
  • 2020-12-29 02:42

    Use 24 hour time to get round the problem like so:

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

    So 2PM equates to 14:00 in 24 hour time. If we remove the colon from the time then we can evaluate it as an integer in our comparison.

    For more information about the date function please see the PHP manual. I have used the following time formatters:

    H = 24-hour format of an hour (00 to 23)

    i = Minutes with leading zeros (00 to 59)

    0 讨论(0)
  • 2020-12-29 02:42

    Use time(), date() and strtotime() functions:

    if(time() > strtotime(date('Y-m-d').' 14:00') {
        //...
    }
    
    0 讨论(0)
提交回复
热议问题