PHP time comparison


DateTime

You can compare time in PHP with DateTime:

$datetime1 = new DateTime('01:00');
$datetime2 = new DateTime('00:00');
$datetime1 > $datetime2; // true

DateTime accepts any any date or time string.

Timezone

The default timezone is UTC:

$datetime = new DateTime('13:00');
$datetime->getTimezone()->getName(); // 'UTC'

You can change the timezone by passing an instance of DateTimeZone to DateTime::setTimezone:

$datetime = new DateTime('24:00');
$datetime->setTimezone(new DateTimeZone('EDT'));

Or pass timezone as the 2nd argument of DateTime:

new DateTime('24:00', new DateTimeZone('America/New_York'));

Example

If you want to check if the current time falls between a range, you can do the following:

$timezone = new DateTimeZone('America/New_York');
$now = new DateTime('now', $timezone);
$start = new DateTime('12:30', $timezone)
$end = new DateTime('13:30', $timezone)
$now >= $start && $now <= $end;

This can be refactored to the function:

function isBetweenTimes(string $start, string $end, string $timezone = 'UTC'): bool
{
    $timezone = new DateTimeZone($timezone);
    $now = new DateTime('now', $timezone);
    $start = new DateTime($start, $timezone);
    $end = new DateTime($end, $timezone);
    return $now >= $start && $now <= $end;
}

Which can be used like so:

$range = '12:30-13:30';
[$start, $end] = explode('-', $range);
isBetweenTimes($start, $end, 'EDT');


Please support this site and join our Discord!