Ok, I have a variable ($incubation) set as 04:00:00.
Then I have another variable ($starttime) set to the current time.
Both are printing out fine.
But I'm trying to get an $endtime from adding the incubation time to the start time.

$incubation = $row['incubation']; //IM GRABBING THIS TIME FROM THE DATABASE. It prints 04:00:00
	
	$starttime = date("H:i:s"); //prints 16:23:39
	
	$endtime = date("H:i:s", $starttime+$incubation);  //prints 20:00:00 when it's suppose to print 20:23:39

Dani AI

Generated

The root cause is mixing formatted time strings with numeric timestamp math. In the example posted by the incubation value comes from the DB as a TIME string (e.g. "04:00:00") and the start time is a formatted string. Adding those strings together will not produce a valid Unix timestamp. As noted, PHP has functions for time math, and pointed out converting an interval to seconds — both are workable. A clearer, safer approach in modern PHP is to use DateTime / DateInterval.

Use DateTime (or DateTimeImmutable) and build a DateInterval from the H:i:s value so the addition is correct and timezone-aware:

$start = new DateTimeImmutable(); // or new DateTimeImmutable($startString)
list($h,$m,$s) = explode(':', $row['incubation']);
$intervalSpec = sprintf('PT%dH%dM%dS', (int)$h, (int)$m, (int)$s);
$end = $start->add(new DateInterval($intervalSpec));
echo $end->format('H:i:s');

Notes and gotchas:

  • DateTime uses PHP's configured timezone. If your app handles users in different zones, construct with a DateTimeZone or store/operate in UTC.
  • Crossing midnight, DST shifts, or intervals >24 hours are handled correctly by DateInterval, unlike naive string math.
  • If you prefer doing it in SQL (so the DB returns the computed end time), MySQL supports ADDTIME/DATE_ADD on TIME/TIMESTAMP columns; that keeps logic close to the data.

See the PHP docs for details: DateTime and DateInterval.

Have a look at the funktion "mktime()" on php.net. It is a very poweful yet simple function for date and time calculations.

Member Avatar for Member #120589

Your method will work if you transform the hours into seconds. I assume your incubation is a time interval (4 hrs) as opposed to a set time (4 am).

function convTime($dbtime){
    list($h, $m, $s) = explode(':', $dbtime);
    return ($h * 3600 ) + ($m * 60 ) + $s;
}

$incubation = convTime($row['incubation']);
$starttime = date("H:i:s"); 
$endtime = date("H:i:s", $starttime+$incubation);

I got a version of this function from somewhere else some time ago. Can't remember where.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.