Reputation: 33
This script returns inconsistent days count. At localhost returns 14 days on the clients server returns 15 days.
$_POST['pickup_time'] = '13:30';
$_POST['dropoff_time'] = '12:00';
$_POST['pickup_date'] = '2013-10-16';
$_POST['dropoff_date'] = '2013-10-30';
$fmt_pickup_date = strtotime($_POST['pickup_date']);
$fmt_dropoff_date = strtotime($_POST['dropoff_date']);
$days = ceil(abs($fmt_dropoff_date - $fmt_pickup_date) / 86400);
if ($vehicles[$v]['vehicle_cal_date']==0)
{
$fmt_pickup_time = str_replace(":", "", $_POST['pickup_time']);
$fmt_dropoff_time = str_replace(":", "", $_POST['dropoff_time']);
if (($fmt_dropoff_time-$fmt_pickup_time)>=1)
{
$days++;
}
}
else { $days++; }
For some dates returns right days count and for some wrong (+1 day).
[pickup_time] => 11:00
[dropoff_time] => 10:00
[pickup_date] => 2013-10-28
[dropoff_date] => 2013-11-01
These dates returns on both servers 4 days wich is right.
Any ideas? What is wrong?
Edit:
It seems that this:
date_default_timezone_set('UTC');
fixes the problem and now the script returns correct days count for both dates. For how long - no idea. I hope that this will fix it for all the dates :)
Upvotes: 1
Views: 119
Reputation: 7316
The issue is really simple, and it's the one I've been repeating around for a long time... And of course it works if you set the timezone to UTC!
Why?
Simply, because of DST. When DST starts or ends, days are not long 24 hours (but 23 or 25 instead). So, when you do the math with 86400 seconds, which are 24 hours, that does not work!
Setting the timezone to UTC, which does not use DST, is a workaround. However, in my opinion the cleanest solution would be to use the DateTime class and let it do the math: http://php.net/datetime Those functions have builtin support for timezones, so they handle DST correctly.
Upvotes: 2
Reputation: 3842
Do not use your own code to make things that php already does.
Try this:
$datetime1 = new DateTime('2013-10-28');
$datetime2 = new DateTime('2013-11-01');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
That output is +4 days.
Hope this helps you
Here is the official documentation about datetime functions and all you can do it with them: http://php.net/manual/en/datetime.diff.php
Upvotes: 1
Reputation: 1189
This may have something to do with the differences in the php setup on localhost vs. the client's server. What I have done in the past is compared the phpinfo() for each to see where the issue could be. Maybe the date configuration for php?
Upvotes: 1