Dani Dani - 8 days ago 6
HTML Question

How to Subtract between two time values using php?

I have done almost everything I found on the internet. I have been trying for the past two days but couldn't get the desire answer.
I just want to subtract two times.
example 22:00:00 - 00:30:00 = 21:30:00

$hourToEatLastMeal = strtotime('00:30:00');
$hourToEatWorkout = strtotime('01:30:00');
$hourBetweenMeal = strtotime('07:30:00');
$lastMealRequested = strtotime($row['lastMeal']); //22:00:00 //value getting from query.

$startEating = $lastMealRequested - $hourToEatLastMeal ;//21:30:00 (want this answer)
$timeToEat = $startEating- $hourBetweenMeal; //14:00:00 (want this answer)
$whenToWorkout = $timeToEat - $hourToEatWorkout; //12:30:00 (want this answer)

$whenToWorkout = date("H:i:s",($whenToWorkout));//12:30:00 (want this answer)
$timeToEat = date("H:i:s",($timeToEat));//14:00:00 (want this answer)
$startEating = date("H:i:s",($startEating));//21:30:00 (want this answer)

Answer

00:30:00 is half past midnight, not 30 minutes. You can subtract 30 minutes with the strtotime function by using -30 minutes.

echo date('H:i:s', strtotime('22:00:00 -30 minutes'));

Other intervals can be done similarly:

echo date('H:i:s', strtotime('22:00:00 -1 hour -30 minutes'));

In your recent example you'd want:

echo date('H:i:s', strtotime($lastMealRequested . ' -30 minutes')); 

because you want the strtotime to do the math, not PHP (or not PHP directly).

Comments