add hours:min:sec to date in PHP

前端 未结 3 565
梦谈多话
梦谈多话 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:35

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

提交回复
热议问题