Posts Tagged ‘date’

relative time in cakephp

function plural($num) {
 if ($num != 1)
 return "s";
}
function getRelativeTime($date) {
 $diff = time() - strtotime($date);
 if ($diff<60)
 return $diff . " second" . plural($diff) . " ago";
 $diff = round($diff/60);
 if ($diff<60)
 return $diff . " minute" . plural($diff) . " ago";
 $diff = round($diff/60);
 if ($diff<24)
 return $diff . " hour" . plural($diff) . " ago";
 $diff = round($diff/24);
 if ($diff<7)
 return $diff . " day" . plural($diff) . " ago";
 $diff = round($diff/7);
 if ($diff<4)
 return $diff . " week" . plural($diff) . " ago";
 return "on " . date("F j, Y", strtotime($date));
}<span>

If you want to use this in your view files, You need a create a file call app.php in view folder.
In your app_controller.php declare a variable


var $view = "App";

your app.php looks something like this

class AppView extends View{
 function convertMysqlDate($dateString)
 {
 return date('M d Y h:s A',strtotime($dateString));
 }
 function plural($num) {
 if ($num != 1)
 return "s";
 }
 function getRelativeTime($date) {
 $diff = time() - strtotime($date);
 if ($diff<60)
 return $diff . " second" . $this->plural($diff) . " ago";
 $diff = round($diff/60);
 if ($diff<60)
 return $diff . " minute" . $this->plural($diff) . " ago";
 $diff = round($diff/60);
 if ($diff<24)
 return $diff . " hour" . $this->plural($diff) . " ago";
 $diff = round($diff/24);
 if ($diff<7)
 return $diff . " day" . $this->plural($diff) . " ago";
 $diff = round($diff/7);
 if ($diff<4)
 return $diff . " week" . $this->plural($diff) . " ago";
 return "on " . date("F j, Y", strtotime($date));
 }
}


source