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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.