note 75004 deleted from function.time by aidan

From: Date: Wed, 15 Apr 2009 16:03:41 +0000
Subject: note 75004 deleted from function.time by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-153328@lists.php.net to get a copy of this message
Note Submitter: joncampell at gmail dot com ---- Time difference both forward and backward, based on tristan's TimeAgo() function :) <?php function timeDiff($timestamp){ $now = time(); //If the difference is positive "ago" - negative "away" ($timestamp >= $now) ? $action = 'away' : $action = 'ago'; switch($action) { case 'away': $diff = $timestamp - $now; break; case 'ago': default: // Determine the difference, between the time now and the timestamp $diff = $now - $timestamp; break; } // Set the periods of time $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade"); // Set the number of seconds per period $lengths = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600); // Go from decades backwards to seconds for ($val = sizeof($lengths) - 1; ($val >= 0) && (($number = $diff / $lengths[$val]) <= 1); $val--); // Ensure the script has found a match if ($val < 0) $val = 0; // Determine the minor value, to recurse through $new_time = $now - ($diff % $lengths[$val]); // Set the current value to be floored $number = floor($number); // If required create a plural if($number != 1) $periods[$val].= "s"; // Return text $text = sprintf("%d %s ", $number, $periods[$val]); return $text . $action; } ?> If anyone knows of an easier way to do this, please comment.

« previous php.notes (#153328) next »