PHP: Get Human Readable Time from Seconds

Linux timestamp is a number of seconds from the Epoch of Linux, large number of seconds. When you are counting the time interval between 2 times or 2 dates, the result is usually in seconds as well. Understandably, it’s everything but user friendly to just present the number of seconds to the users, e.g. 153297 s since last visit.

To display the time interval in a human readable format instead of in seconds, you can use the following function:

function getHumanTime($s) {
	$m = $s / 60;
	$h = $s / 3600;
	$d = $s / 86400;
	if ($m > 1) {
		if ($h > 1) {
			if ($d > 1) {
				return (int)$d.' d';
			} else {
				return (int)$h.' h';
			}
		} else {
			return (int)$m.' m';
		}
	} else {
		return (int)$s.' s';
	}
}

This is what I used for Usable Databases to display length of time since the user’s last visit to a certain page. d indicates day, h hour, m minute and s seconds. This function requires a number of seconds as input and convert it into human readable time periods such as x hours or x days.

3 thoughts on “PHP: Get Human Readable Time from Seconds”

Comments are closed.

Scroll to Top