Re: difference in time
| From: | Aschwin Wesselius | Date: | Tue, 11 Mar 2008 11:09:20 +0000 |
| Subject: | Re: difference in time | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-271264@lists.php.net to get a copy of this message | ||
Lamp Lists wrote:
hi to all! on one eZine site, I have to show when the article is posted but as difference from NOW. like "posted 32 minutes ago", or "posted 5 days ago". is there already sucha php/mysql function? thanks.Hi, I don't know about existing functions but you can use this: function time_to_units($time) {
$years = floor($time / 60 / 60 / 24/ 365);
$time -= $years * 60 * 60 * 24 * 365;
$months = floor($time / 60 / 60 / 24 / 30);
$time -= $months * 60 * 60 * 24 * 30;
$weeks = floor($time / 60 / 60 / 24 / 7);
$time -= $weeks * 60 * 60 * 24 * 7;
$days = floor($time / 60 / 60 / 24);
$time -= $days * 60 * 60 * 24;
$hours = floor($time / 60 / 60);
$time -= $hours * 60 * 60;
$minutes = floor($time / 60);
$time -= $minutes * 60;
$seconds = $time;
$amount = 0;
$unit = '';
if ($years > 0) {
$amount = $years;
$unit = ' year';
if ($years > 1) {
$unit.= 's ';
}
}
elseif ($months > 0) {
$amount = $months;
$unit = ' month';
if ($months > 1) {
$unit.= 's ';
}
}
elseif ($weeks > 0) {
$amount = $weeks;
$unit = ' week';
if ($weeks > 1) {
$unit.= 's ';
}
}
elseif ($days > 0) {
$amount = $days;
$unit = ' day';
if ($days > 1) {
$unit.= 's ';
}
}
elseif ($hours > 0) {
$amount = $hours;
$unit = ' hour';
if ($hours > 1) {
$unit.= 's ';
}
}
elseif ($minutes > 0) {
$amount = $minutes;
$unit = ' minute';
if ($minutes > 1) {
$unit.= 's ';
}
}
elseif ($seconds > 0) {
$amount = $seconds;
$unit = ' second';
if ($seconds > 1) {
$unit.= 's ';
}
}
return $amount.$unit;} $posted = ; // some timestamp in the past $now = time(); // as current as possible $diff = ($now - $posted); echo "posted ".time_to_units($diff)." ago"; I hope this helps ;-) -- Aschwin Wesselius /'What you would like to be done to you, do that to the other....'/