Calculate day difference between two dates [PHP]

Asked

Viewed 5,474 times

3

Good afternoon to you all! I did some research before asking the question, but I did not get an answer to my question in any of them.

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

I did a functional exercise, which is the best way to adapt it to receive the dates from 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!

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 on 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 on IDEONE.


The function strtotime makes the interpretation of string as per 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 format, and you prefer to use another conversion criteria, this post may be useful:

How to invert dates in php, regardless of format?

  • Thank you Bacco, all the help was very good, but it was your help that I ended up using! Thank you very much !

4

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

Then use the method DateTime::diff 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 method diff return an instance of the object DateInterval.

See here the table of symbols that can be used to format the difference between dates (DateInterval).

Browser other questions tagged

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