Search code examples
phptimestrtotime

PHP compare between two times 24 hour format after 00:00 and before


I am trying to compare two times one of which is in 12 hour format and the other is in 24 hour format, that is after 12am.

$time = date( 'H:i:s', current_time( 'timestamp', 0 ));
$open = '18:00';
$closed = '01:30';
if ( $time < $open || $time > $closed)
{
//do something
}

this is always failing it is something to do with the 01.30 because if I do anything less than 00:00 e.g. 23.30:

$time = date( 'H:i:s', current_time( 'timestamp', 0 ));
$open = '18:00';
$closed = '23:30';

The above works.

I have also tried strtotime like this without success.

if ( $time < strtotime($open) || $time > strtotime($closed))

How can I evaluate between 6pm and 2am in the morning?


Solution

  • Since you are only comparing the current time (time right now), logically you don't have to worry about tomorrow's time. You only need to compare if you are inside/outside today's opening/closing times.

    <?php
    // SET RELEVANT TIMEZONE
    date_default_timezone_set('Europe/Dublin');
    
    // CURRENT UNIX TIMESTAMP
    $time_now = time();
    
    // TODAY AT 18:00:00 (24 HOUR) UNIX TIMESTAMP
    $opening_time = DateTime::createFromFormat('H:i:s', '18:00:00')->format("d-M-Y H:i:s"); // 11-May-2018 18:00:00
    
    // TODAY AT 01:30:00 (24 HOUR) UNIX TIMESTAMP
    $closing_time = DateTime::createFromFormat('H:i:s', '01:30:00')->format("d-M-Y H:i:s"); // 11-May-2018 01:30:00
    
    // WE ARE CLOSED IF:
    // TIME NOW IS AFTER CLOSING TIME TODAY (01:30:00)
    // AND TIME NOW IS BEFORE OPENING TIME TODAY (18:00:00)
    if($time_now > strtotime($closing_time) && $time_now < strtotime($opening_time))
    {
        echo "Sorry, we are closed!";
    }
    else
    {
        echo "We are open, come on in!";
    }