PHP: Get Human Readable Time from Seconds

by Yang Yang on September 29, 2010

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.

Subscribe to Kavoir: blog feed

You should also read:

Rikudou_Sennin August 20, 2012 at 6:51 am

Isn’t it better to simply use date() ?

Yang Yang August 20, 2012 at 12:02 pm

Hmmm, that would be a terrific idea. Can you write some code? I can publish it as a guest post from you!

Jay Tillz January 22, 2013 at 11:49 pm

I guess you couldn’t use date(); ;)

Comments on this entry are closed.

Previous post:

Next post: