Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way of adding a time interval in PHP?

Tags:

php

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 ?

like image 993
Nelson Teixeira Avatar asked Sep 26 '13 19:09

Nelson Teixeira


2 Answers

You could first explode the interval and then get the hours, minutes, seconds, and then use DateTime's add() to add the interval, like so:

$interval = '50:25:10';
$datestring = '2013-01-05 10:55:15';    
list($hours, $minutes, $seconds) = explode(':', $interval); 

$date = new DateTime($datestring);    
$date->add(new DateInterval('PT'.$hours.'H'.$minutes.'M'.$seconds.'S'));
echo $date->format('Y-m-d H:i:s');

Demo!

like image 92
Amal Murali Avatar answered Nov 15 '22 15:11

Amal Murali


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:

DateInterval

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");
like image 43
Adam Zielinski Avatar answered Nov 15 '22 15:11

Adam Zielinski