How can I use DateTime in PHP to get the next occurrence of a specific time of day, such at 5PM, relative to the current time – either 5PM today if the current time is < 5PM, or 5PM tomorrow if the current time today >= 5PM.
The failing code I’m using is:
date_default_timezone_set("America/New_York");
$today = new DateTime('next 5PM');
echo $today->format('Y-m-d H:i:s') . "n";
These work:
$today = new DateTime('5PM');
$today = new DateTime('today 5PM');
$today = new DateTime('tomorrow 5PM');
$today = new DateTime('yesterday 5PM');
But I wanted to using one statement get the DateTime for 5PM today if the current time is < 5PM, or the DateTime for 5PM tomorrow, if the current time now is >= 5PM.
Can this simply be done in one statement with DateTime? If so, does it depend on PHP version?
I get Fatal Errors trying:
$today = new DateTime('next 5PM');
Thanks,
Jim
2
Answers
If you cannot find the solution in PHP library, just program it.
Hint:
Take DateTime object from the current time – $now.
Get $now->format(‘H’) and convert it to integer
Compare the value to 17 and depending on result, use ‘today 5PM’ or ‘tomorrow 5PM’
If you do everything right, you need 3-7 lines of code depending on your coding style
You can compare current hour with 5PM like below