Discover time interval

Asked

Viewed 184 times

-1

I’m trying to figure out the time interval between two strings with the strtotime.

One has the complete temple and the other varies from minutes to hours, the problem is that when there are minutes, when using the strtotime, It turns minutes (Ex: 3:00 min turns 3:00:00 hrs)

How can I know the time interval?
I want the duration + start subtracted by the current time of the machine to arrive at the value 00:02:04.

//O xml me retornar assim
$duracao = '03:04'; //As vezes pode variar até horas!
$inicio  = '2019-06-02 13:07:03'; //Sempre virá nesse formato

//No caso real seria o date(Y-m-d H:i:s);
//Mas de exemplo use esta string:
$temp_maquina = '2019-06-02 13:08:03';

$t = (strtotime($duracao) + strtotime($inicio)) - strtotime($temp_maquina);

echo date("h:i:s", $t);
  • Can you give an example and how should the output be? I did not understand much the question.

  • can be in thousandth the time remaining, I want to use in an interval in javascript, is a web radio system, to get the json back to each song, instead of calling it all the time

  • No, in my case my problem is that strtotime is turning minutes into hours by increasing zeroes

2 answers

1

In PHP there is a function that makes the calculation of this time difference, you need to inform the date as DateTime and use the function diff to carry out the operation, follows the documentation complete.

Remember that this function will only work for version 5.3.0 or higher of PHP.

date_default_timezone_set('America/Sao_Paulo'); //Fuso horario de brasilia

// calcula milissegundos
$t = microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);

// Datas para determinar o intervalo
$data_1 = new DateTime(date('2019-06-02 00:00:00.000000')); //primeira data
$data_2 = new DateTime(date('Y-m-d H:i:s.'.$micro, $t)); //segunda data
$intervalo = $data_1->diff($data_2); //função para encontrar o intervalo
// saida
echo $intervalo->format('%y/') . 
$intervalo->format('%m/') . 
$intervalo->format('%d ') . 
$intervalo->format('%h:') . 
$intervalo->format('%i:') . 
$intervalo->format('%s.') . 
$intervalo->format('%F');

Output example:

0/0/0 15:6:17.441868

1


First, it is important to keep in mind two concepts:

  • a date and time represent specific points in time: a date corresponds to a specific point in the calendar (a given day, month and year) and a time corresponds to a specific time in the day
  • a duration is a quantity of time unrelated to a specific date and time

To make the difference clearer, consider the 2 examples below:

  • the meeting will be at 3 pm
  • the meeting lasted 3 hours

In the first example, I am referring to a specific time of the day. In the second example, I’m referring to the length of the meeting: the amount of time it took (and in that case, I didn’t say what time it started or ended - I just said the amount of time, with no reference to the time itself).

What can confuse these two concepts is the fact that they both use the same words (days, hours, minutes, etc). To make matters worse, it is customary to write them the same way. For example: "10:00:00" can be either 10:00 in the morning or a duration of 10:00 (as many timers often show). But although they are often written the same way, they are different concepts that should not be confused.

Obviously we can relate them (a date added to a duration results in another date, the difference between two dates/times is a duration, etc.), but they are not the same thing.


That said, the function strtotime works with dates and times, but not with durations (it may even "work" in some cases, but it will be by coincidence). We can see in documentation that when it receives a string in the "xx:yy" format, it is interpreted as "hour:minute" (the hours of the day, not a duration of x hours and y minutes). So anyway, you shouldn’t use strtotime for durations.

To work with durations, PHP (in versions >= 5.3.0) has the class DateInterval. Unfortunately it cannot convert a string in "xx:yy" format directly to a duration, so we have to do this manually:

$duracao = '03:04';
$partes = explode(':', $duracao);
$len = count($partes);
if ($len == 2) { // só tem minutos e segundos
  $horas = 0;
  $minutos = $partes[0];
  $segundos = $partes[1];
} else if ($len == 3) { // tem horas, minutos e segundos
  $horas = $partes[0];
  $minutos = $partes[1];
  $segundos = $partes[2]; 
}
// cria o DateInterval
$d = new DateInterval("PT{$horas}H{$minutos}M{$segundos}S");

Here I am considering the cases "03:04" (3 minutes and 4 seconds), or "01:03:04" (1 hour, 3 minutes and 4 seconds), which you said are the possible cases (if there is more, just add in the code above).

Then I create the DateInterval, and the string passed to the builder should be in format ISO 8601: the letter "P" at the beginning indicates a duration, and the letter "T" indicates that the following fields correspond to the time (hours, minutes and seconds). Then I put the respective values, followed by your time unit ("H" for hours, "M" for minutes and "S" for seconds).

Then just add this DateInterval at the DateTime initial, and then subtract the other date:

$inicio  = new DateTime('2019-06-02 13:07:03');
$temp_maquina = new DateTime('2019-06-02 13:08:03');
$result = $inicio->add($d)->diff($temp_maquina);
echo $result->format("%H:%I:%S"); // 00:02:04

The builder of DateTime receives the strings you specified (but you can simply use new DateTime() for the current date/time). Next method add sum the date and duration, resulting in another DateTime.

Then we subtract $temp_maquina (using the method diff) and the result is another DateInterval, containing the difference between the dates. Finally, we use the method format to format the duration. The result is:

00:02:04

Corresponding to a duration of 2 minutes and 4 seconds.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.