在PHP中添加hours:min:sec至今 [英] add hours:min:sec to date in PHP

查看:112
本文介绍了在PHP中添加hours:min:sec至今的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在日期中添加hh:mm:ss.我该怎么办?

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

我尝试了以下方法,但是当小时是字符串时,它可以工作,但是当添加时间类似于MySQL Date时间时,则无法工作.

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 ?

如何添加它?

推荐答案

使用 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');

您需要将时间分解为正确的DateInterval格式,但这很容易通过explode();

You would need to break your time down into the right DateInterval format but that is easily done with 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');

演示

这篇关于在PHP中添加hours:min:sec至今的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆