Syed Syed - 1 month ago 7
PHP Question

get upcoming time that may be of the next date

I have following code that always returns time of the same date,

$time = time();
if ($time < strtotime("09:00:00") || $time > strtotime("17:00:00")) {
$nextTime = strtotime("09:00:00");
return $nextTime;
}


I want to return upcoming time that may be of the next date.

Expected result: If time is before 9AM it should return 9AM time of the same day, or if time is after 5PM it should return 9AM time of next day.

Answer

You should use the DateTime object to compare the date and time:

function dateCompare($dateToCompare)
{
    $nineAM = clone $dateToCompare;
    $nineAM->setTime(9, 0, 0);
    $fivePM = clone $dateToCompare;
    $fivePM->setTime(17, 0, 0);

    if ($dateToCompare < $nineAM) {
        return $nineAM;
    }

    if ($dateToCompare > $fivePM) {
        $nineAM->modify('+1 day');
        return $nineAM;
    }

    return $dateToCompare;
}

var_dump(dateCompare(new DateTime()));
Comments