calculating days between php dates

Asked

Viewed 19,261 times

2

Guys I’m trying to check the difference in days, based on 2 dates.

Well my code is like this:

$data_inicio = new DateTime("2016-07-10");
$data_fim = new DateTime("2016-07-13");

// Resgata diferença entre as datas
$dateInterval = $data_inicio->diff($data_fim);
$dias = $dateInterval->d + ($dateInterval->y * 12);

echo $dias;

Good if I inform the following values:

$data_inicio = new DateTime("2016-07-10");
$data_fim = new DateTime("2016-07-13");

My return and 3, so far so good. But when I put:

$data_inicio = new DateTime("2016-07-10");
$data_fim = new DateTime("2017-08-13");

My return continues to be 3, ie the system ignored the months and years. Someone knows how to solve this?

2 answers

11


You can do it like this:

<?php 
    $data_inicio = new DateTime("2016-07-10");
    $data_fim = new DateTime("2017-07-10");

    // Resgata diferença entre as datas
    $dateInterval = $data_inicio->diff($data_fim);
    echo $dateInterval->days;

    //365
 ?>

There’s a difference between d and days you can see the specifications here

  • Thanks @Ricardo Mota, simple and direct, helped me a lot, thanks.

  • Boy, you saved my day, thanks @Ricardo Mota

4

You can use this function:

<?php
$date1=date_create("2016-07-10");
$date2=date_create("2017-08-13");
$diff=date_diff($date1,$date2);
echo $diff->format("%a");
?>

//Saída: 399 
  • very good, that’s right. And much simpler. But I need the output to be numerical only. How do I change this?

  • 2

    echo $diff->format("%a");

Browser other questions tagged

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