Jump to content

News

Sign in to follow this  
  • entries
    3
  • comments
    0
  • views
    1,012

Contributors to this blog

Code leaked.

Sign in to follow this  
Administrator

340 views

PHP Custom Time Ago Function

This PHP code reads the value of the date field on form post. This value will be passed as an argument to the custom timeago() function.

In timeago() function the given date is converted into timestamp using PHP built-in strtotime(). And, this timestamp is subtracted from the current timestamp to calculate elapsed time.

The time elapsed from the given date till now is used to calculate the time ago string. The code is,

<?php
	$strTimeAgo = ""; 
	if(!empty($_POST["date-field"])) {
		$strTimeAgo = timeago($_POST["date-field"]);
	}
	function timeago($date) {
	   $timestamp = strtotime($date);	
	   
	   $strTime = array("second", "minute", "hour", "day", "month", "year");
	   $length = array("60","60","24","30","12","10");

	   $currentTime = time();
	   if($currentTime >= $timestamp) {
			$diff     = time()- $timestamp;
			for($i = 0; $diff >= $length[$i] && $i < count($length)-1; $i++) {
			$diff = $diff / $length[$i];
			}

			$diff = round($diff);
			return $diff . " " . $strTime[$i] . "(s) ago ";
	   }
	}
	
?>
Sign in to follow this  


0 Comments


Recommended Comments

There are no comments to display.

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now

×
×
  • Create New...