PHP Calculate Time Since

GeekThis remains completely ad-free with zero trackers for your convenience and privacy. If you would like to support the site, please consider giving a small contribution at Buy Me a Coffee.

While working on a few changes to this website, I needed to code or find a relative time function for PHP. A function that will turn a timestamp or unix_timestamp into how long ago it was performed. For instance, if the timestamp is from yesterday, it would return the string of “1 day ago”, up to values of years. But there was an issue. Whenever I went online to find a function to do this, they all had a ton of nested if statements and a huge list of cases also. So I’m here to show you a simple way to code a PHP function to get relative time.

Now, how about we get started with having PHP do our work while we just provide it the correct data to work with.

<?php
function time_relative($time) {
	/*
		If you are importing a string timestamp (2013-08-14T21:35:16.000Z)
		Use the $epoch = strtotime($time) function. This gets a unix_timestamp
		which we can use to find the difference in seconds.

		If you are not using a string timestamp and just importing the unix_timestamp
		$epoch = $time;
	*/
	$epoch = strtotime($time);
	$now = time();

	// Get the difference in time. This is how many seconds between now and the timestamp provided
	$dif = $now - $epoch;

	$times = array(
		array('term' => 'second', 'divide' => false),
		array('term' => 'minute', 'divide' => 60),
		array('term' => 'hour', 'divide' => 3600),
		array('term' => 'day', 'divide' => 86400),
		array('term' => 'week', 'divide' => 604800),
		array('term' => 'month', 'divide' => 2592000),
		array('term' => 'year', 'divide' => 31536000)
	);

	for($i = 0; $i < count($times); $i++) {
		if(isset($times[$i+1])) {
			$next = $times[$i+1];
		}else{
			$next = false;
		}

		if($next == false || $dif < $next['divide']) {
			if($times[$i]['divide'] != false) {
				$time = floor($dif / $times[$i]['divide']);
			}else{
				$time = $dif;
			}
			if($time == 1) {
				return $time.' '.$times[$i]['term'].' ago';
			}else{
				return $time.' '.$times[$i]['term'].'s ago';
			}
		}
	}
	return '';
}

As you can see, we have an array of times. This is what replaces all of the if statements in other versions of this code that you will see scattered around the internet. I set the singular term for the time, such as minute, hour day, etc. It will append a ’s' to the end if plural. Then each time array has a divide value. This is what we divide the difference by to get the amount for that specific value. For days, we divide by the numbers of seconds in a day.

In the for loop, we loop the amount of times values we have. We check if the times array has an array in the next spot. If it doesn’t, meaning it’s the last and greatest time frame, we have to return that. If it does have an array, we check to see if our difference in times is less than that divide amount.

We then divide the time difference by the array’s divide value. If divide == false or 0, we just return the time since you cannot divide by zero, and some values we don’t want divided.

We perform one last check, seeing if the value is greater than 1. If the value is greater than 1, we have to make the term pluaral, else we just return the term with the value.

Related Posts

PHP - Check if Production or Sandbox

Use PHP to check of your site is on your development server or uploaded to the production server.

Setup PHP Development Web Server Quickly inside of Windows

Quickly setup a PHP development enviornment by using the built in PHP web server with no additional software required.

PHP Dynamic Subdomains

How to setup dynamic subdomains with PHP to give users a custom domain for their profile page.

Parsing AWStats with PHP

Parse Awstat files using PHP including information about the awstats file format.