...

View Full Version : Compute time difference / time_since



ptmuldoon
05-22-2008, 04:42 PM
I found this time_since function via a google search, and it works well. But I'm unsure on how to have it includes the minutes. Currently it shows X day, X hours,



function time_since($original) {
// array of time period chunks
$chunks = array(
array(60 * 60 * 24 * 365 , 'year'),
array(60 * 60 * 24 * 30 , 'month'),
array(60 * 60 * 24 * 7, 'week'),
array(60 * 60 * 24 , 'day'),
array(60 * 60 , 'hour'),
array(60 , 'minute'),
);

$today = time(); /* Current unix time */
$since = $today - $original;

// $j saves performing the count function each time around the loop
for ($i = 0, $j = count($chunks); $i < $j; $i++) {

$seconds = $chunks[$i][0];
$name = $chunks[$i][1];

// finding the biggest chunk (if the chunk fits, break)
if (($count = floor($since / $seconds)) != 0) {
// DEBUG print "<!-- It's $name -->\n";
break;
}
}

$print = ($count == 1) ? '1 '.$name : "$count {$name}s";

if ($i + 1 < $j) {
// now getting the second item
$seconds2 = $chunks[$i + 1][0];
$name2 = $chunks[$i + 1][1];

// add second item if it's greater than 0
if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
$print .= ($count2 == 1) ? ', 1 '.$name2 : ", $count2 {$name2}s";
}
}
return $print;
}
$time = '1211373000';
echo time_since($time);

ptmuldoon
05-22-2008, 05:00 PM
Nevermind, I'm learning :)

I simply added this to the code:



// now get the third item
$minutes3 = $chunks[$i + 2][0];
$name3 = $chunks[$i + 2][1];

// add third item if it's greater than 0
if (($count3 = floor(($since - ($seconds * $count)) / $minutes3)) != 0) {
$print .= ($count3 == 1) ? ', 1 '.$name3 : ", $count3 {$name3}s";
}

Fou-Lu
05-23-2008, 02:55 AM
Good good, gotta start somewhere, learning the ideas behind how things work is a great start! I always find that dates/times are a pain no matter what language you are using (if you are using manual stuff).
Once you get proficient with the manual control of the time - PHP has IMO the greatest date/time handling of any language I've used. You may want to keep this link (http://ca3.php.net/manual/en/ref.datetime.php) in mind. You will be surprised what php can do for you automatically!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum