By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

PHP Function to Return Time Units From TimeStamp

This php function will return seconds, minutes, hours, days, weeks, months, and years.

Edited: 2013-04-24 22:07

By. BlueBoden

Quickly wrote this function to deal with a common problem in my PHP Scripts, that is how to output time units – fairly easy once you sit down and take the time to code it – anyway here it is:

<?php

function CallTime($TimeGiven) {
  $TimeArray = array();
  $TimeArray[0] = round($TimeGiven);
  $TimeArray[1] = 'Seconds';
  if($TimeGiven >= 60) {
  	$TimeArray[0] = round($TimeGiven/60);
  	$TimeArray[1] = 'Mins';
    if($TimeGiven >= 60) {
  	  $TimeArray[0] = round($TimeGiven/60);
  	  $TimeArray[1] = 'Hours';
	  if($TimeGiven >= 24) {
  	    $TimeArray[0] = round($TimeGiven/60);
  	    $TimeArray[1] = 'Days';
	    if($TimeGiven >= 365) {
  	      $TimeArray[0] = round($TimeGiven/365);
  	      $TimeArray[1] = 'Years';
	    } else if($TimeGiven >= 31) {
  	      $TimeArray[0] = round($TimeGiven/31);
  	      $TimeArray[1] = 'Months';
	    } else if($TimeGiven >= 7) {
  	      $TimeArray[0] = round($TimeGiven/7);
  	      $TimeArray[1] = 'Weeks';
	    }
	  }
    }
  }
  return $TimeArray;
}

?>

The function currently only accepts a Unix TimeStamp, I'll improve it later to accept both UTC and UNIX if i get the time – i will be going to work now, so i don't have time – but it doesn't take long to add UTC to the function, 5mins maybe.

The function returns an array, 0 containing the count, and 1 containing the units.