Page 1 of 1
calculating days between two dates
Posted: Sat Apr 27, 2013 7:33 am
by drors
I have two fields showing dates.
I need to calculate the number of days between them , then presenting the result
in a text field (tpl flile).
I'm not sure if this is correct but script should be something as the following.
Of course i also need to know where to insert it.
$From = $_GET(option 1);
$To = $_GET(option 2);
$datediff = $To - $From;
echo floor($datediff/(60*60*24));
Re: calculating days between two dates
Posted: Sat Apr 27, 2013 9:49 am
by mecha_godzilla
Hi,
If you use PHP 5.3 or later, it's a good idea to rely on the in-built functions - here is an example from the PHP manual:
Code: Select all
// http://uk.php.net/manual/en/datetime.diff.php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
The reason for using the in-built functions is because they can take into account things like daylight saving time adjustments, leap years, etc., but this sometimes makes the results more accurate at the cost of seeming less intuitive - this is more likely to happen in situations where you're calculating the difference in years, because PHP is calculating these values at the seconds level and therefore (to it at least) once all the daylight saving time adjustments and leap years are taken into account, the seconds might not add up to a full year even though to us we can confidently say that a year has passed between 1st January 1970 and 1st January 1971.
If you prefer not to use these kind of functions for compatibility reasons, it's usually a good idea to convert the dates to timestamps using strtotime() and calculate the number of days that way, similar to how your code works at the moment:
Code: Select all
$start = strtotime('2010-01-25');
$end = strtotime('2010-02-20');
$days_between = ceil(abs($end - $start) / 86400); // same as 60*60*24
echo $days_between;
HTH,
Mecha Godzilla
Re: calculating days between two dates
Posted: Sun Apr 28, 2013 5:25 am
by drors
Hi Mecha
i would prefer the second solution but in my case dates are not fixed.
They should be retrieved according the input of the user.
Thanks
Dror