php: simple way to convert time into readable time

Joined
12 Feb 2006
Posts
17,628
Location
Surrey
can't seem to find a way to do this and i'm sure it must be really simple. i have googled a lot but i think i am googling the wrong phrase to get the results i am after.

i have lets say a comment system which records when the comment was posted and then adds 30 days and then records when the comment will expire and get removed.

now i want to work out how long until the comment expires and show this to the user, so i subtracted the expire time from the current time() leaving a number like 2710380.

how do i work out how much this number is in a readable time like 1 day 3 hours and 21 seconds? i'm hoping there is just a simple way like i do the following $timeLeft/60/60*24 to get days etc?

thanks
 
Probably overkill and hacked together from the function I found on php.net:

PHP:
<?php
$timestamp_post 	= 	1225544372;	// Nov. 1st 2008
$timestamp_expire 	= 	strtotime('+1 month', $timestamp_post);

$timestamp_difference = FormatTimeDiff(time(), $timestamp_expire, 'wdhms');
echo sprintf('Time until comment is deleted: %d weeks, %d days, %d hours, %d seconds',
				$timestamp_difference['w'],
				$timestamp_difference['d'],
				$timestamp_difference['h'],
				$timestamp_difference['s']);


/*
 * Formatted time-difference between $t1 and $t2 (seconds)
 * The difference in seconds is distributed into years, months, etc. as specified by $format.
 * $format is a string containing characters y, f, w, d, h, m or s, for years, months, weeks, days, hours, minutes or seconds, resp.
 * Output is an array containing keys y, f, etc., with the numerical values.
 * Values are negative if $t1 is more than $t2.
 * http://uk.php.net/time
*/

function FormatTimeDiff($t1, $t2=null, $format='yfwdhms'){
 $t2 = $t2 === null ? time() : $t2;
 $s = abs($t2 - $t1);
 $sign = $t2 > $t1 ? 1 : -1;
 $out = array();
 $left = $s;
 $format = array_unique(str_split(preg_replace('`[^yfwdhms]`', '', strtolower($format))));
 $format_count = count($format);
 $a = array('y'=>31556926, 'f'=>2629744, 'w'=>604800, 'd'=>86400, 'h'=>3600, 'm'=>60, 's'=>1);
 $i = 0;
 foreach($a as $k=>$v){
  if(in_array($k, $format)){
   ++$i;
   if($i != $format_count){
    $out[$k] = $sign * (int)($left / $v);
    $left = $left % $v;
   }else{
    $out[$k] = $sign * ($left / $v);
   }
  }else{
   $out[$k] = 0;
  }
 }
 return $out;
} 
?>

Output:

Time until comment is deleted: 2 weeks, 6 days, 11 hours, 28 seconds
 
Back
Top Bottom