add hours:min:sec to date in PHP

China☆狼群 提交于 2020-07-03 06:09:40

问题


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'

OutPut:

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

How Can I Add this?


回答1:


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

Demo




回答2:


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

Should work also.

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

Can be the solution.




回答3:


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


来源:https://stackoverflow.com/questions/33037598/add-hoursminsec-to-date-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!