add hours:min:sec to date in PHP

前端 未结 3 566
梦谈多话
梦谈多话 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:31
     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.

    0 讨论(0)
  • 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');
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题