Created
September 20, 2011 11:12
-
-
Save Kalyse/1228876 to your computer and use it in GitHub Desktop.
My_View_Helper_FuzzyDate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class My_View_Helper_FuzzyDate extends Zend_View_Helper_Abstract { | |
public function __construct() { | |
} | |
public function fuzzyDate($dateFrom, $dateTo) { | |
// array of time period chunks | |
$chunks = array( | |
array(60 * 60 * 24 * 365, 'year'), | |
array(60 * 60 * 24 * 30, 'month'), | |
array(60 * 60 * 24 * 7, 'week'), | |
array(60 * 60 * 24, 'day'), | |
array(60 * 60, 'hour'), | |
array(60, 'minute'), | |
); | |
$original = $dateFrom; | |
$now = $dateTo; | |
$since = $now - $original; | |
$message = ($now > $original) ? null : null; | |
// If the difference is less than 60, we will show the seconds difference as well | |
if ($since < 60) { | |
$chunks[] = array(1, 'second'); | |
} | |
// $j saves performing the count function each time around the loop | |
for ($i = 0, $j = count($chunks); $i < $j; $i++) { | |
$seconds = $chunks[$i][0]; | |
$name = $chunks[$i][1]; | |
// finding the biggest chunk (if the chunk fits, break) | |
if (($count = floor($since / $seconds)) != 0) { | |
break; | |
} | |
} | |
$print = ($count == 1) ? '1 ' . $name : $count . ' ' . $name . 's'; | |
if ($i + 1 < $j) { | |
// now getting the second item | |
$seconds2 = $chunks[$i + 1][0]; | |
$name2 = $chunks[$i + 1][1]; | |
// add second item if it's greater than 0 | |
if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) { | |
$print .= ($count2 == 1) ? ', 1 ' . $name2 : ', ' . $count2 . ' ' . $name2 . 's'; | |
} | |
} | |
return $message . $print .= ($now > $original) ? " ago" : ""; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment