Add 'x' number of hours to date

Solution 1:

You may use something like the strtotime() function to add something to the current timestamp. $new_time = date("Y-m-d H:i:s", strtotime('+5 hours')).

If you need variables in the function, you must use double quotes then like strtotime("+{$hours} hours"), however better you use strtotime(sprintf("+%d hours", $hours)) then.

Solution 2:

An other solution (object-oriented) is to use DateTime::add

Example:

<?php

$now = new DateTime(); //now
echo $now->format('Y-m-d H:i:s'); // 2021-09-11 01:01:55

$hours = 36; // hours amount (integer) you want to add
$modified = (clone $now)->add(new DateInterval("PT{$hours}H")); // use clone to avoid modification of $now object
echo "\n". $modified->format('Y-m-d H:i:s'); // 2021-09-12 13:01:55

Run script


  • DateTime::add PHP doc
  • DateInterval::construct PHP doc

Solution 3:

You can use strtotime() to achieve this:

$new_time = date("Y-m-d H:i:s", strtotime('+3 hours', $now)); // $now + 3 hours

Solution 4:

Correct

You can use strtotime() to achieve this:

$new_time = date("Y-m-d H:i:s", strtotime('+3 hours', strtotime($now))); // $now + 3 hours

Solution 5:

You can also use the unix style time to calculate:

$newtime = time() + ($hours * 60 * 60); // hours; 60 mins; 60secs
echo 'Now:       '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $newtime) ."\n";