add hours:min:sec to date in PHP

前端 未结 3 670
梦谈多话
梦谈多话 2021-01-18 08:05

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

3条回答
  •  耶瑟儿~
    2021-01-18 08:43

    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

提交回复
热议问题