skip to Main Content

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


  1. If you cannot find the solution in PHP library, just program it.

    Hint:

    1. Take DateTime object from the current time – $now.

    2. Get $now->format(‘H’) and convert it to integer

    3. 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

    Login or Signup to reply.
  2. You can compare current hour with 5PM like below

    date_default_timezone_set("America/New_York");
    
    if (date('H') < 17) {
       $next = new DateTime('yesterday 5PM');
    }
    else{
        $next = new DateTime('tomorrow 5PM');
    }
    
    
    echo $next->format('Y-m-d H:i:s') . "n";
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search