I want to add time to an existing date. I have 2 string variables:
$date = "2013-01-05 10:55:15"; $interval = "50:25:10";
I want to calculate the final date “2013-01-07 13:20:25”. The hours in time can be bigger than 23, meaning that this interval can be greater than a whole day.
What’s the best way to do this ?
Advertisement
Answer
Use DateTime API:
$date = new DateTime("2013-01-05 10:55:15"); $date->add(new DateInterval("PT50H25M10S"));
then you can convert it back to string with the same date format you would use with date()
function, if you want to:
$string = $date->format("Y-m-d H:i:s");
For more information about the DateInterval
definition, visit this page:
The format starts with the letter P, for “period.” Each duration period is represented by an integer value followed by a period designator. If the duration contains time elements, that portion of the specification is preceded by the letter T.
Here are some simple examples. Two days is P2D. Two seconds is PT2S. Six years and five minutes is P6YT5M.
so in this case PT50H25M10S
means 50 hours, 25 minutes, and 10 seconds
Note that DateInterval is available only since PHP 5.3, if you have to use lower version, you could use something like this:
$time = strtotime("2013-01-05 10:55:15"); $time += 55*60*60 + 25*60 + 10; $newDate = date("Y-m-d H:i:s");