1 Replies - 6174 Views - Last Post: 19 November 2014 - 06:28 AM

#1 Glorfindal   User is offline

  • Java Enthusiast
  • member icon

Reputation: 37
  • View blog
  • Posts: 606
  • Joined: 31-December 08

Function that formats the difference between a given unix time and now

Post icon  Posted 04 November 2014 - 03:39 PM

This function returns a nicely formatted time that describes the difference between a given time (in unix time format) and the current time. The function is about 50 lines long with comments throughout and designed to be fairly easy to modify. :)/>/> If the given time was less than two days (this value can be changed quite easily) ago it writes amount of days (if applicable), hours (if applicable) and minutes that have passed since the time. Otherwise it simply outputs a formatted date (mm/dd/yyyy).

Function:
function getFormattedDate($timeOld)
{
	$timeDifference = time() - $timeOld;
	$hour = 3600;
	if($timeDifference < $hour*48)
	{
		//Less than a minute ago
		if($timeDifference < 60)
		{
			return "Less than a minute ago";
		}
		//A minute ago
		if($timeDifference >= 60 and $timeDifference < 120)
		{
			return "One moment ago";
		}
		//Between a minute and a hour ago
		if($timeDifference >= 120 and $timeDifference < 3600)
		{
			$minutes = round($timeDifference/60, 0);
			return "$minutes minutes ago";
		}
		//One hour ago
		if($timeDifference >= 3600 and $timeDifference < 7200)
		{
			return "One hour ago";
		}
		if($timeDifference >= 7200 and $timeDifference < $hour*25)
		{
			$hours = round($timeDifference/3600, 0);
			if($hours = 24 or $hours = 25) {
				return "1 Day ago";
			} else {
				return "$hours Hours ago";
			}
		}
		if($timeDifference >= $hour*25 and $timeDifference < $hour*48)
		{
			$hours = (round($timeDifference/3600, 0)) - 24;
			return "1 Day $hours Hours ago";
		}
	}
	else
	{
		$dt = new DateTime("@$timeOld");
		return $dt->format('m/d/Y');
	}
}


Example Usage:
//Test date that is always exactly 25 hours ago
$testDate = time() - 60*60*25;
echo getFormattedDate($testDate);


Is This A Good Question/Topic? 0
  • +

Replies To: Function that formats the difference between a given unix time and now

#2 Snijder   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 18-November 14

Re: Function that formats the difference between a given unix time and now

Posted 19 November 2014 - 06:28 AM

thanks for this
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1