I'm using this to echo interval number of days between two dates, but the second line echoes a float number.
echo (mktime(0,0,0,10,27,2013)-mktime(0,0,0,8,18,2013))/(3600*24).'<br>';
echo (mktime(0,0,0,10,28,2013)-mktime(0,0,0,8,18,2013))/(3600*24).'<br>';
Result:
70
71.041666666667
Can anyone tell me why? Thanks!
Because when dividing in PHP, you'll always receive float.
To get int you have to round it or cast it.
$int = (int) $float;
or
$int = round($float, 0);
One exception is when both operands are integers (or strings that can be cast to integers) and they are divisible.
Result: 71.041666666667. Can anyone tell me why? Thanks!
I changed to date.timezone = Asia/Shanghai in php.ini and now am getting integer (correct) result.
Because Asia/Shanghai
timezone doesn't use DST. For example try timezone Europe/Berlin
(who uses DST), and you will see that you are having the same problem :
date_default_timezone_set('Asia/Shanghai');
echo (mktime(0,0,0,10,28,2013)-mktime(0,0,0,8,18,2013))/(3600*24); # 71
date_default_timezone_set('Europe/Berlin');
echo (mktime(0,0,0,10,28,2013)-mktime(0,0,0,8,18,2013))/(3600*24); # 71.041666666667
DST is used [blue] | DST is no longer used [orange] | DST has never been used [red]
That's why I always suggest to use DateTime instead of mktime(), strtotime() and similar function. DateTime handles leap years and time-zones correctly.
$f = new DateTime('2013-08-18');
$t = new DateTime('2013-10-28');
echo $f->diff($t)->days; # 71
Or one-liner (PHP >= 5.4) :
echo (new DateTime('2013-08-18'))->diff(new DateTime('2013-10-27'))->days; # 71