Add hours: min: sec to date in PHP

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

I tried with the following, but it works when the hour is a string, but when adding time similarly to MySQL Date time it does not work.

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

I am trying to get a solution for the following:

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

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

Output:

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

How can i add this?

+4
source share
3 answers

Use DateInterval():

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

You need to break your time down into the desired DateInterval format, but this is easy to do with explode();

Here's what it might look like:

$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]));
$timeA->add($timeB);
echo $timeA->format('Y-m-d H:i:s');

Demo

+6
source

: HH: MM: SS ?

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

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

DateTime, @John Conde, :

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

, :

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

, :

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

$initialTime = new DateTime($initial);
$intervalTime = new DateInterval($interval);
$initialTime->add($intervalTime);
echo $initialTime->format('Y-m-d H:i:s');
+2
 print date('Y-m-d H:i:s',strtotime($timeA." +03 hour +05 minutes +01 seconds"));  

Should also work.

So:

$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));

May be a solution.

+1
source

Source: https://habr.com/ru/post/1610935/


All Articles