One of the latest features I’ve added to my sports fishing portal was the nice date feature. Instead of showing PHP formatted date and time, I wanted to display time since the action took place, like “4 hours ago”, “2 days ago”, “1 minute ago” and so on.
<?php
function nicetime($date) {
if(empty($date)) {
return "ERROR: No date provided";
}
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
$now = time();
$unix_date = strtotime($date);
// check validity of date
if(empty($unix_date)) {
return "ERROR: Invalid date";
}
// is it future date or past date
if($now > $unix_date) {
$difference = $now - $unix_date;
$tense = "ago";
}
else {
$difference = $unix_date - $now;
$tense = "from now";
}
for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
$difference /= $lengths[$j];
}
$difference = round($difference);
if($difference != 1) {
// $periods[$j] .= "s"; // plural for English language
$periods = array("seconds", "minutes", "hours", "days", "weeks", "months", "years", "decades"); // plural for international words
}
return "$difference $periods[$j] {$tense}";
}
?>
Use <?php echo nicetime($date);?> to call the function, where $date is a variable holding your desired date, properly formatted in PHP/MySQL. You can also pass a date directly using the standard format – date(‘Y-m-d G:i:s’), but for obvious reasons it’s better to prior assign it to a fixed variable.



Loading ...