Jump to content

Date difference


speedy33417

Recommended Posts

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

$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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.