How to subtract a specific time with the system time in php?

1

How can I make the $ total variable give me a result in hour format? Now with this code, the only thing I achieve is to subtract the hours, but not the minutes, and it only shows me a number. example: 07:45 - 03:35 = 4. I would like instead of giving me 4 something like: 03:10.

$fin = '07:45';               
$hora = date("H:i");  
$total = $fin - $hora;

echo "EL evento empezara en $total";
    
asked by Luis Cesar 13.06.2018 в 03:22
source

2 answers

1

A simple function should suffice for the subtraction of hours:

Do the following:

$hora_actual=date("H:i");
$fin = '07:45'; 
$resultado=date("H:i:s",strtotime("00:00") +strtotime($fin) - strtotime($hora_actual) );
echo $resultado;

This should work, but keep in mind that date("H:i") , pulls the current time according to the time zone of your server, so that configuration is left to you.

Remember also that it would only work in subtraction of horas and would not take into account the dates .

    
answered by 13.06.2018 / 05:07
source
1

You can create two DateTime objects, one with the fixed time 07:45 and one with the current time.

Then you use diff to calculate the difference between the two objects, making calculations about the different groups of differences in the object that will throw you diff .

For example:

$dateStart = new DateTime("07:45:00");
$dateEnd   = new DateTime();
$dateInterval = $dateEnd->diff($dateStart);

$strResult = sprintf(
    '%d:%02d:%02d', //formato de salida
    ($dateInterval->d * 24) + $dateInterval->h, //horas
    $dateInterval->i, //minutos
    $dateInterval->s  //segundos
);
echo "El evento empezará en $strResult";

Using diff is the best way to calculate differences between dates, because it throws you a complete object with all kinds of differences. To give you an idea, this is all the information that will be in the object $dateInterval of the code above. It will let you know, if necessary, not only how many hours / minutes / seconds there are between two dates, but also how many weeks, months, years ... and more information.

object(DateInterval)#3 (15) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(0)
  ["d"]=>
  int(0)
  ["h"]=>
  int(3)
  ["i"]=>
  int(5)
  ["s"]=>
  int(50)
  ["weekday"]=>
  int(0)
  ["weekday_behavior"]=>
  int(0)
  ["first_last_day_of"]=>
  int(0)
  ["invert"]=>
  int(0)
  ["days"]=>
  int(0)
  ["special_type"]=>
  int(0)
  ["special_amount"]=>
  int(0)
  ["have_weekday_relative"]=>
  int(0)
  ["have_special_relative"]=>
  int(0)
}
    
answered by 13.06.2018 в 04:43