Home » Php » mysql – add hours:min:sec to date in PHP

mysql – add hours:min:sec to date in PHP

Posted by: admin July 12, 2020 Leave a comment


I am trying to add hh:mm:ss with the date. How can i do it?

I tried with the following but it works when the hour is string, but when adding time is similar to MySQL Date time it is not working.

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

I am trying to get solution for the following:

$timeA= '2015-10-09 13:40:14'; 

$timeB = '03:05:01';  // '0000-00-00 03:05:01'


$timeA + $timeB = 2015-10-09 16:45:15 ?

How Can I Add this?

How to&Answers:

Use DateInterval():

$timeA = new DateTime('2015-10-09 13:40:14');
$timeB = new DateInterval('PT3H5M1S'); // '03:05:01'; 
echo $timeA->format('Y-m-d H:i:s');

You would need to break your time down into the right DateInterval format but that is easily done with explode();

Here’s how that might look:

$parts = array_map(function($num) {
    return (int) $num;
}, explode(':', '03:05:01'));

$timeA = new DateTime('2015-10-09 13:40:14');
$timeB = new DateInterval(sprintf('PT%uH%uM%uS', $parts[0], $parts[1], $parts[2]));
echo $timeA->format('Y-m-d H:i:s');



 print date('Y-m-d H:i:s',strtotime($timeA." +03 hour +05 minutes +01 seconds"));  

Should work also.


$timeA= '2015-10-09 13:40:14'; 

$timeB = vsprintf(" +%d hours +%d minutes +%d seconds", explode(':', '03:05:01')); 

print date('Y-m-d H:i:s',strtotime($timeA.$timeB));

Can be the solution.


You may also convert the time into seconds with this approach from: Convert time in HH:MM:SS format to seconds only?

$time = '03:05:01';
$seconds = strtotime("1970-01-01 $time UTC");

Then you could add the seconds to

$currentTime = '2015-10-10 13:40:14';
$newTime = date("Y-m-d H:i:s", strtotime( $currentTime.'+'.$seconds.' seconds'));

If you prefer to use the DateTime objects offered by @John Conde, here are two ways to convert the time string into the format:

$formattedTime = preg_replace("/(\d{2}):(\d{2}):(\d{2})/","PT$1H$2M$3S","03:05:11");

or, as you read it from the database:

select concat(hour(last_modified),'H',minute(last_modified),'M',second(last_modified),'H') from people;

So a more general code approach would be:

$initial = 'some time';
$interval = 'the interval value';

$initialTime = new DateTime($initial);
$intervalTime = new DateInterval($interval);
echo $initialTime->format('Y-m-d H:i:s');