Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/249.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中添加小时:分钟:秒到日期_Php_Mysql_Date_Add - Fatal编程技术网

在PHP中添加小时:分钟:秒到日期

在PHP中添加小时:分钟:秒到日期,php,mysql,date,add,Php,Mysql,Date,Add,我正在尝试添加hh:mm:ss和日期。我怎么做 我尝试了以下方法,但当小时是字符串时,它可以工作,但当添加时间类似于MySQL日期时间时,它就不工作了 $new_time = date("Y-m-d H:i:s", strtotime('+5 hours')); 我正在尝试获得以下问题的解决方案: $timeA= '2015-10-09 13:40:14'; $timeB = '03:05:01'; // '0000-00-00 03:05:01' 输出: $timeA + $time

我正在尝试添加hh:mm:ss和日期。我怎么做

我尝试了以下方法,但当小时是字符串时,它可以工作,但当添加时间类似于MySQL日期时间时,它就不工作了

$new_time = date("Y-m-d H:i:s", strtotime('+5 hours'));
我正在尝试获得以下问题的解决方案:

$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 ?
如何添加此项?

使用:

您需要将时间分解为正确的DateInterval格式,但使用
explode()
可以轻松完成此操作

这可能看起来是这样的:

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

也应该有效

因此:


可以是解决方案。

您也可以通过以下方法将时间转换为秒:

然后,您可以将秒添加到

$currentTime = '2015-10-10 13:40:14';
$newTime = date("Y-m-d H:i:s", strtotime( $currentTime.'+'.$seconds.' seconds'));
如果您更喜欢使用@John Conde提供的DateTime对象,以下是将时间字符串转换为格式的两种方法:

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

在my DB中,此格式的值将为'03:05:01'显示我转换为所有?您可以将日期时间格式分解为较小的部分,并动态生成日期。但这比这还要多。那么,如果我需要在这个格式中添加第二个日期怎么办?“2015-10-09 13:40:14”@johnUm,你也这么做吗
$currentTime = '2015-10-10 13:40:14';
$newTime = date("Y-m-d H:i:s", strtotime( $currentTime.'+'.$seconds.' seconds'));
$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');