Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add hours:min:sec to date in PHP

Tags:

date

php

mysql

add

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

OutPut:

$timeA + $timeB = 2015-10-09 16:45:15 ?

How Can I Add this?

like image 268
DonOfDen Avatar asked Oct 09 '15 11:10

DonOfDen


People also ask

How can add hours minutes and seconds in PHP?

The DateTime::add() function is an inbuilt function in PHP which is used to add an amount of time (days, months, years, hours, minutes and seconds) to the given DateTime object.

What is the use of Strtotime function in PHP?

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.

How can I get the difference between two dates in PHP?

The date_diff() function returns the difference between two DateTime objects.

Can you compare time in PHP?

In order to compare those two dates we use the method diff() of the first DateTime object with the second DateTime object as argument. The diff() method will return a new object of type DateInterval .


1 Answers

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

like image 140
John Conde Avatar answered Oct 01 '22 07:10

John Conde