Calculate difference between dates and times coming from time and separate dates

Asked

Viewed 55 times

0

Good morning, I want to create a code where I can tell how many days and hours in a date range, which are shown separately. like this:

Start time = 12:07:07 - Start Date = 10/15/2018 - Final Time = 12:07:08 - Final Date = 10/16/2018 - TIME = 24:00:01 - TOTAL DAYS = 01

Can someone help me? I’ve tried everything I know, search the internet and managed to adapt to a code that shows only the interval of hours, but wanted to improve it to show the interval between dates also.

follows the code below

      $entrada = $row_pesquisar['horainicio'];
      $saida = $row_pesquisar['horafinal'];
      $row_pesquisar1['horainicio'] = explode(":",$entrada);
      $row_pesquisar1['horafinal'] = explode(":",$saida);
      $acumulador1 = ($row_pesquisar1['horainicio'][0] * 3600) + ($row_pesquisar1['horainicio'][1] * 60) + $row_pesquisar1['horainicio'][2];
      $acumulador2 = ($row_pesquisar1['horafinal'][0] * 3600) + ($row_pesquisar1['horafinal'][1] * 60) + $row_pesquisar1['horafinal'][2];
      $resultado = $acumulador2 - $acumulador1;
      $hora_ponto = floor($resultado / 3600);
      $resultado = $resultado - ($hora_ponto * 3600);
      $min_ponto = floor($resultado / 60);
      $resultado = $resultado - ($min_ponto * 60);
      $secs_ponto = $resultado; 
      $tempo = $hora_ponto.":".$min_ponto.":".$secs_ponto;
      echo $tempo;

1 answer

0

The code below should work as you need:

<?php

    //Seta a data padrão pro php reconhecer o formato d/m/Y
    date_default_timezone_set('America/Sao_Paulo');

    //Cria a data de inicio e fim convertendo a string em formato brasileiro pro formato americano
    $data_inicio = new DateTime(date('Y-m-d H:i:s', strtotime('15-10-2018 12:07:07')));
    $data_final = new DateTime(date('Y-m-d H:i:s', strtotime('16-10-2018 12:18:08')));

    //Pega a diferença das datas
    $diff = $data_final->diff($data_inicio);

    //Exibe resultado formatado

    echo $diff->format('TOTAL DE DIAS = %d');
    echo "<br>";

    //realiza o calculo pra pegar intervalo de horas
    echo "TEMPO = ". (($diff->d * 24) + $diff->h ) .':'. $diff->format('%i:%s');

Online test: http://sandbox.onlinephpfunctions.com/code/013b3cc9c3bb99d3ca089a989c66e846423c62a0

http://php.net/manual/en/function.date-default-timezone-set.php http://php.net/manual/en/datetime.diff.php

  • Good morning Edson, I tried to do with the model you sent me, but I couldn’t adapt, what I have here is the same as the one in the link below, only the field hours is not divided in the same way: https://www.horlogeparlante.com/calcular-dura%C3%A7%C3%B5es.html

  • You can concatenate the time as needed: '15-10-2018' . $hora_inicio . ':'. $min_inicio . ':' . $seg_inicio

  • I understood, but my case is this: in the comic book I have the columns "horainicio, horafinal, created and modified", the columns of the hour are of type time and the dates are of type date only. I did so because I have a form to change the information as soon as I need it, so can I put $row_search['horainicio'] and $row_search['created'] within the same $data_inicio = new Datetime(date('Y-m-d H:i:s', strtotime()?

  • Yes, you can test... Just concatenate the 2 by separating by a space. date('Y-m-d H:i:s', [...] serves only to format the string in the format that Datetime understands. If it already comes from the database in this format it does not need to be inside. Just call the Datetime by passing the string

  • Edson I did as told me and as the date and the team comes already formatted bank, but it did not work, I think I’m doing wrong. $data_inicio = (.$row_pesquisar['created'] .$row_pesquisar['horainicio']);&#xA;$data_final = (.$row_pesquisar['modified'] .$row_pesquisar['horafinal']); ESSA É MENSAGEM DE ERRO Parse error: syntax error, unexpected '.' in C:\Program Files (x86)\EasyPHP-5.3.5.0\www\sistema-de-service reports.php on line 180

  • There is a point at the beginning of its concatenation $data_inicio = (. <- and you need to concatenate with a space like this: $data_inicio = ($row_pesquisar['created'].' '.$row_pesquisar['horainicio']);

  • Edson really was that, but this excerpt is not showing the time echo "TIME = ". ((($diff->d * 24) + $diff->h ) . ':'. $diff->format('%i:%s'); LOOK AT THE FULL CODE: $start_date = ($row_search['created']. ' '.$row_search['horainicio']); $data_final = ($row_search['modified']. '.'$row_search['endtime']); $diff = $data_final-$data_start; echo $diff; echo "<br>"; echo "TIME = ". (($diff->d * 24) + $diff->h ) . ':'. $diff->format('%i:%s');

  • $diff = $data_final->diff($data_inicio); You have to call the function and not subtract from each other. Subtracting even from the... But it would be another case, you would have to convert the date to UNIX. Change that line. And another, you have to create Datetime: $data_inicio = new DateTime($row_pesquisar['modified'].' '.$row_pesquisar['horafinal'])

  • Good afternoon Edson, I had even put the Datetime, but then appeared the following error: Fatal error: Call to Undefined Function Datetime() in C: Program Files (x86) Easyphp-5.3.5.0 www service system reports.php on line 181, so I had taken, but if you have to enter, I’ll see if I can get around that mistake.

  • Datetime is an object, for instance it needs to put the word new before

  • Edson, it worked perfectly, thank you very much. You’re a beast.

  • Wow, good guy. Good luck there

  • Edson good morning, look at me bothering you again. My code looks like this and is working perfectly, date_default_timezone_set('America/Bahia'); $data_inicio = new Datetime($row_search['created'].' '.$row_search['horainicio']); $data_final = new Datetime($row_search['modified'].' '.$row_search['final time']); $diff = $data_final->diff($start_date); but if I wanted to count only the days from Monday to Friday, I could adapt it to the same code.

  • Putz, I guess I’d have to change all the logic but I don’t know how to do it... just ask another question specifically about this, people will help you.. does not forget to explain well and put your code in question. Success

  • Thank you so much Edson, you’ve helped me so much.

Show 10 more comments

Browser other questions tagged

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