Posted by & filed under Programming.

Can’t take credit for all of this, but I also don’t remember where the code that I started with came from.

days_ago is a function that will take two dates and return a more human friendly version of dates. So if you pass today’s date and yesterday’s date it will return “1 day ago.”

function days_ago($startdate, $enddate)
/*	Returns a human friendly version of the date difference
	between the two dates	*/
	{
	/*	Get the difference in seconds between the two timestamps.
		Converts to absolute value so that it doesn't matter which
		date is greater.	*/
	$ts_difference = abs(strtotime($enddate) - strtotime($startdate));
	if ($ts_difference < 60)
	//	Seconds
		{
		$number = $ts_difference;
		if ($number==1)
			{
			$retval = $number.' second';
			}
		else
			{
			$retval = $number.' seconds';
			}
		}
	elseif ($ts_difference >=60 && $ts_difference < 3600)
	//	Minutes
		{
		$number = floor($its_difference / 60);
		if ($number==1)
			{
			$retval = $number.' minute';
			}
		else
			{
			$retval = $number.' minutes';
			}
		}
	elseif ($ts_difference >=3600 && $ts_difference < 86400)
	//	Hours
		{
		$number = floor($ts_difference / 3660);
		if ($number==1)
			{
			$retval = $number." hour";
			}
		else
			{
			$retval = $number.' hours';
			}
		}
	else
	//	Days
		{
		$number = floor($ts_difference / 86400);
		if ($number==1)
			{
			$retval = $number.' day';
			}
		else
			{
			$retval = $number.' days';
			}
		}
        if ($number > 45) {
            return ""; // Don't return if more than 45 days ago
        }
	return $retval." ago";
	}

One note, for what I needed this for it needed to return an empty string if greater than 45 days. The very last conditional checks for that and returns the empty string. If you would rather it return 1000 days then just delete that conditional.

You could also take it farther and do weeks, months, years, decades, whatever.

Trackbacks/Pingbacks

  1.  WordPress recent posts as JSON | Nutt.net

Leave a Reply

Your email address will not be published. Required fields are marked *