Calculate days between two dates

Asked

Viewed 34 times

0

Guys I have the following code

$date = date('d-m-Y', strtotime($row['data']));
                $data_preset = date('Y/m/d');
                $diferenca = strtotime($data_preset) - strtotime($row['data']);
                $dias = floor($diferenca / (60 * 60 * 24)); 

        echo '<p style="color:#6a727a;">Data do pedido(a):</p><p class="color">'. $row['data'] .'</p></div></div><br>';
        if($dias<=15){
            echo '<p class="actived">Pedido feito a '. $dias .' dias, está dentro do prazo </p></br>';
      
        }else{
            echo '<p class="foraD">Pedido feito a '. $dias .' dias, está fora do prazo, por favor verificar  </p></br>';
        
        }

it works fine but I registered a test request on day 2020-09-10 was to accuse that makes 17 days the request was made but is accusing that makes 18 days

i also registered a test request made today 27/09/2020 and is accusing that already 1 day ago the request was made and not 0 days

$Row['data'] is the while that retrieve the date. and I’m making this post at 21:14 on 27/09/2020

  • If it is a pattern that is responding to the calculation with 1 day more than expected in all situations, why not adjust the code with -1? $dias = floor($diferenca / (60 * 60 * 24)) - 1;

1 answer

0


Good morning buddy, how are you?

I did in mine as follows, (do not take into account if you are messy, because I am a person who is just creating the site itself in a system, for my employees to use, finally this one

$hoje = date('Y-m-d');
$venc = $mostrar[3]; // já vem formatado em 'Y-m-d'

// converte as datas para o formato timestamp
 $d1 = strtotime($hoje); 
 $d2 = strtotime($venc);

// verifica a diferença em segundos entre as duas datas e divide pelo número de segundos que um dia possui - resumindo, da o resultado em dias (multipliquei por *-1 porque esta retornando um valor negativo, exemplo -4dias, multiplicando *-1 remove o '-'

$dias = (($d2 - $d1)/86400)*-1;
  • I was thinking, it can be easy to solve too, create a formatting before loading the dates, in the following form date('Y-m-d') what can be happening with your code, is adding together the hours in which it was saved, giving a chopped value and when being bigger than ,5 this rounding to larger and vice versa, try to change also the format of the datapreset, is in a way that the strtotime does not recognize

  • I did the way you said but it didn’t work, what worked was your top code, and in my to tidy I found out that it was just add date_default_timezone_set('America/Sao_paulo');helped me a lot xD

Browser other questions tagged

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