PHP division resulting in NaN - maybe related to DateTime functions
I'm currently trying to do a "time ago" function but for some reason, it ends up giving me a NaN for one of the results.
I'm using a slightly modified version of this piece of code (found at: http://www.sitepoint.com/create-your-own-twitter-widget-3/ )
if ($this->DateFormat == 'friendly') {
// friendly date format
$ival = $now->diff($stime);
$yr = $ival->y;
$mh = $ival->m + ($ival->d > 15);
if ($mh > 11) $yr = 1;
$dy = $ival->d + ($ival->h > 15);
$hr = $ival->h;
$mn = $ival->i + ($ival->s > 29);
if ($yr > 0) {
if ($yr == 1) $date = 'last year';
else $date = $yr . ' years ago';
}
else if ($mh > 0) {
if ($mh == 1) $date = 'last month';
else $date = $mh . ' months ago';
}
else if ($dy > 0) {
if ($dy == 1) $date = 'yesterday';
else if ($dy < 8) $date = $dy . ' days ago';
else if ($dy < 15) $date = 'last week';
else $date = round($dy / 7) . ' weeks ago';
}
else if ($hr > 0) {
$hr += ($ival->i > 29);
$date = $hr . ' hour' . ($hr == 1 ? '' : 's') . ' ago';
}
else {
if ($mn < 3) $date = 'just now';
else $date = $mn . ' minutes ago';
}
}
(the problematic line is the one with theround($dy / 7)
I created a set of possible values to test the outcomes and it gives me a NaN for a date of -29 days. The thing is that it only happens to do that when I repeat the function over and over. If I just test -29 days alone, it outputs me the correct 4 weeks value.
Any idea on how can I avoid/fix this?
Edit
This is most likely a bug in PHP.
If I make the code do the division and rounding twice, the NaN never appears.
// do estimate of how many weeks ago
$round = round($days / 7, 0);
$round = round($days / 7, 0);
$date = $round . ' weeks ago';
I noticed this because in my test loops, the first value that triggered the weeks calculation (given that I was making more than one calculation) would give the NaN.
Answer
Solution:
interestingly my hack had worked on similar problem. I just put this before the operations with the date:
and the rest worked. Obviously $y1, $y2 etc. are NAN somehow... Running XAMP, Win 7 x64, DENWER, PHP v 5.3+
Answer
Solution:
While I personally believe this was bug (I found some bug submissions and stackoverflow questions having similar problems) it doesnt seem to be happening anymore after going from 5.3.1 to 5.3.5.
This is a simplified code that would give NaN for me
(I was running XAMPP 1.7.3 (PHP 5.3.1) on Windows)