/ Published in: PHP
A simple function for converting a php timestamp (integer) to a user frindly format. Examples: 10 Seconds ago, 4 Days ago. The function converts timestamp to U.F. format only if the timestamp is earlyer than one week. Otherwise it uses $dateFormat argument to display the date.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
<?php function user_friendly_date($timestamp, $echo = false, $dateFormat = 'm/d/Y H:i:s') { $ufdate = ''; $elapsed = $now - $timestamp; if($elapsed <= 0) $ufdate = 'Now'; else if($elapsed == 1) $ufdate = "1 Second ago"; else if($elapsed < 60) $ufdate = "{$elapsed} Seconds ago"; else if($elapsed < 3600) //One hour in seconds { $secs = $elapsed%60; $ufdate = "{$disp} Minute" . ($disp == 1 ? '' : 's') ." ago"; } else if($elapsed < 86400) //One day in seconds { $ufdate = "{$disp} Hour" . ($disp == 1 ? '' : 's') ." ago"; } else if($elapsed < 604800) //One week in seconds { $ufdate = "{$disp} Day" . ($disp == 1 ? '' : 's') ." ago"; } if($echo) echo $ufdate; return $ufdate; } //Usage $tenSecsAgo = $now - 10; $oneMinuteAgo = $now - 60; $thirtyNineMinsAgo = $now - (39 * 60); //minutes * seconds $elevenHoursAgo = $now - (11 * 60 * 60); //hours * minutes * seconds $twoDaysAgo = $now - (2 * 24 * 60 * 60); //days * hours * minutes * seconds echo "<p>\n"; echo user_friendly_date($tenSecsAgo), " <br>\n"; echo user_friendly_date($oneMinuteAgo), " <br>\n"; echo user_friendly_date($thirtyNineMinsAgo), " <br>\n"; echo user_friendly_date($elevenHoursAgo), " <br>\n"; echo user_friendly_date($twoDaysAgo), " <br>\n"; echo "</p>"; ?>