speedy33417 Posted June 2, 2010 Share Posted June 2, 2010 I'm using DATETIME to store time in a database and would like to calculate the time difference between two times like so: $timeAdded = "2010-03-01 09:01:00"; $currentTime = "2010-03-01 09:02:00"; //here comes the magic //....... echo "This user was added $timeDifference"; It should result something like: This user was added 1 minute ago. This user was added 17 minutes ago. This user was added 3 hours ago. What's the best way to do this? Link to comment https://forums.phpfreaks.com/topic/203686-date-difference/ Share on other sites More sharing options...
premiso Posted June 2, 2010 Share Posted June 2, 2010 $timeSince = time_since(strtotime($timeAdded)); echo $timeSince; 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; if($since > 604800) { $print = date("M jS", $original); if($since > 31536000) { $print .= ", " . date("Y", $original); } return $print; } // $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"; return $print . " ago"; } Snippet came from: http://snippets.dzone.com/posts/show/3044 Link to comment https://forums.phpfreaks.com/topic/203686-date-difference/#findComment-1066883 Share on other sites More sharing options...
Daniel0 Posted June 2, 2010 Share Posted June 2, 2010 Or if you're using PHP 5.3.0 or later: http://php.net/manual/en/datetime.diff.php Link to comment https://forums.phpfreaks.com/topic/203686-date-difference/#findComment-1066890 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.