Calculate days difference between two dates [PHP] [duplicate]

3

Good afternoon everyone! I did research before asking the question, but I did not get an answer for my doubt in any of them.

I need help getting the following code to receive the two dates by the $ _GET variable, example (.php? data1 = 23-09-16 & data2 = 20-09-16). Basically present in full the dates inserted and show the difference of days between them.

I did a functional exercise, what is the best way to adapt it to receive dates abroad?

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>teste dias</title>
</head>
<body>

<?php

$br="<br>";

$agora=mktime(17,00,00,9,23,2016); 
$agora=date("F d, Y - g:i:s a", $agora);
echo "Hoje e agora são: ".$agora.$br;

$dia1=mktime(0,0,0,1,1,2016);
$dia2=mktime(0,0,0,2,1,2016);

echo (($dia2-$dia1)/60/60/24)." dias".$br;
echo $br;

?>

</body>
</html>

Thank you!

    
asked by anonymous 23.09.2016 / 18:09

2 answers

6

For the DD-MM-AA format specified in the question, we need to separate the date components to convert the year to 4 digits:

$data1 = explode( '-', $_GET['data1'] );
$data2 = explode( '-', $_GET['data2'] );

echo $dia1 = mktime( 0, 0, 0, $data1[1], $data1[0], 2000+$data1[2] );
echo $dia2 = mktime( 0, 0, 0, $data2[1], $data2[0], 2000+$data2[2] );

echo ( $dia2 - $dia1 ) / 86400;

See working at IDEONE .


A simpler way, if you can already send the value with 4 digits in the year, is this:

$dia1=strtotime( $_GET['data1'] );
$dia2=strtotime( $_GET['data2'] );

echo ( $dia2 - $dia1 ) / 86400;

See working at IDEONE .


The function strtotime interprets the string as the separator.

  • Dates with / are considered as MM/DD/AAAA ;

  • Dates with - are considered as DD-MM-AAAA ;


If your dates are in MM / DD / YY, and you'd prefer to use another conversion criterion, this posting might be useful:

  

How to invert dates in php regardless of format?

    
23.09.2016 / 18:21
4

Use the DateTime::createFromFormat method to transform the date into an object DateTime from a format.

Next, use the DateTime::diff method to compute the difference between dates.

$d1 = DateTime::createFromFormat('d-m-y', $_GET['data1'])
$d2 = DateTime::createFromFormat('d-m-y', $_GET['data2'])

$d2->diff($d1)->format('%a');

The diff method will return an instance of the DateInterval object.

Here is the table of symbols that can be used to format the difference between dates (% with%).

23.09.2016 / 18:17