Related
I need to convert seconds to "Hour:Minute:Second".
For example: "685" converted to "00:11:25"
How can I achieve this?
You can use the gmdate() function:
echo gmdate("H:i:s", 685);
One hour is 3600sec, one minute is 60sec so why not:
<?php
$init = 685;
$hours = floor($init / 3600);
$minutes = floor(($init / 60) % 60);
$seconds = $init % 60;
echo "$hours:$minutes:$seconds";
?>
which produces:
$ php file.php
0:11:25
(I've not tested this much, so there might be errors with floor or so)
here you go
function format_time($t,$f=':') // t = seconds, f = separator
{
return sprintf("%02d%s%02d%s%02d", floor($t/3600), $f, ($t/60)%60, $f, $t%60);
}
echo format_time(685); // 00:11:25
Use function gmdate() only if seconds are less than 86400 (1 day) :
$seconds = 8525;
echo gmdate('H:i:s', $seconds);
# 02:22:05
See: gmdate()
Run the Demo
Convert seconds to format by 'foot' no limit* :
$seconds = 8525;
$H = floor($seconds / 3600);
$i = ($seconds / 60) % 60;
$s = $seconds % 60;
echo sprintf("%02d:%02d:%02d", $H, $i, $s);
# 02:22:05
See: floor(), sprintf(), arithmetic operators
Run the Demo
Example use of DateTime extension:
$seconds = 8525;
$zero = new DateTime("#0");
$offset = new DateTime("#$seconds");
$diff = $zero->diff($offset);
echo sprintf("%02d:%02d:%02d", $diff->days * 24 + $diff->h, $diff->i, $diff->s);
# 02:22:05
See: DateTime::__construct(), DateTime::modify(), clone,
sprintf()
Run the Demo
MySQL example range of the result is constrained to that of the TIME data type, which is from -838:59:59 to 838:59:59 :
SELECT SEC_TO_TIME(8525);
# 02:22:05
See: SEC_TO_TIME
Run the Demo
PostgreSQL example:
SELECT TO_CHAR('8525 second'::interval, 'HH24:MI:SS');
# 02:22:05
Run the Demo
Other solutions use gmdate, but fail in edge cases where you have more than 86400 seconds. To get around this, we can simply compute the number of hours ourselves, then let gmdate compute the remaining seconds into minutes/seconds.
echo floor($seconds / 3600) . gmdate(":i:s", $seconds % 3600);
Input: 6030
Output: 1:40:30
Input: 2000006030
Output: 555557:13:50
// TEST
// 1 Day 6 Hours 50 Minutes 31 Seconds ~ 111031 seconds
$time = 111031; // time duration in seconds
$days = floor($time / (60 * 60 * 24));
$time -= $days * (60 * 60 * 24);
$hours = floor($time / (60 * 60));
$time -= $hours * (60 * 60);
$minutes = floor($time / 60);
$time -= $minutes * 60;
$seconds = floor($time);
$time -= $seconds;
echo "{$days}d {$hours}h {$minutes}m {$seconds}s"; // 1d 6h 50m 31s
If you don't like accepted answer or popular ones, then try this one
function secondsToTime($seconds_time)
{
if ($seconds_time < 24 * 60 * 60) {
return gmdate('H:i:s', $seconds_time);
} else {
$hours = floor($seconds_time / 3600);
$minutes = floor(($seconds_time - $hours * 3600) / 60);
$seconds = floor($seconds_time - ($hours * 3600) - ($minutes * 60));
return "$hours:$minutes:$seconds";
}
}
secondsToTime(108620); // 30:10:20
gmdate("H:i:s", no_of_seconds);
Will not give time in H:i:s format if no_of_seconds is greater than 1 day (seconds in a day).
It will neglect day value and give only Hour:Min:Seconds
For example:
gmdate("H:i:s", 89922); // returns 0:58:42 not (1 Day 0:58:42) or 24:58:42
Here is a one liner that handles negative seconds and more than 1 day worth of seconds.
sprintf("%s:%'02s:%'02s\n", intval($seconds/60/60), abs(intval(($seconds%3600) / 60)), abs($seconds%60));
For Example:
$seconds= -24*60*60 - 2*60*60 - 3*60 - 4; // minus 1 day 2 hours 3 minutes 4 seconds
echo sprintf("%s:%'02s:%'02s\n", intval($seconds/60/60), abs(intval(($seconds%3600) / 60)), abs($seconds%60));
outputs: -26:03:04
I have already explained this here
pasting that answer here as well
For till 23:59:59 hours you can use PHP default function
echo gmdate("H:i:s", 86399);
Which will only return the result till 23:59:59
If your seconds is more than 86399 than
with the help of #VolkerK answer
$time = round($seconds);
echo sprintf('%02d:%02d:%02d', ($time/3600),($time/60%60), $time%60);
will be the best options to use ...
write function like this to return an array
function secondsToTime($seconds) {
// extract hours
$hours = floor($seconds / (60 * 60));
// extract minutes
$divisor_for_minutes = $seconds % (60 * 60);
$minutes = floor($divisor_for_minutes / 60);
// extract the remaining seconds
$divisor_for_seconds = $divisor_for_minutes % 60;
$seconds = ceil($divisor_for_seconds);
// return the final array
$obj = array(
"h" => (int) $hours,
"m" => (int) $minutes,
"s" => (int) $seconds,
);
return $obj;
}
then simply call the function like this:
secondsToTime(100);
output is
Array ( [h] => 0 [m] => 1 [s] => 40 )
See:
/**
* Convert number of seconds into hours, minutes and seconds
* and return an array containing those values
*
* #param integer $inputSeconds Number of seconds to parse
* #return array
*/
function secondsToTime($inputSeconds) {
$secondsInAMinute = 60;
$secondsInAnHour = 60 * $secondsInAMinute;
$secondsInADay = 24 * $secondsInAnHour;
// extract days
$days = floor($inputSeconds / $secondsInADay);
// extract hours
$hourSeconds = $inputSeconds % $secondsInADay;
$hours = floor($hourSeconds / $secondsInAnHour);
// extract minutes
$minuteSeconds = $hourSeconds % $secondsInAnHour;
$minutes = floor($minuteSeconds / $secondsInAMinute);
// extract the remaining seconds
$remainingSeconds = $minuteSeconds % $secondsInAMinute;
$seconds = ceil($remainingSeconds);
// return the final array
$obj = array(
'd' => (int) $days,
'h' => (int) $hours,
'm' => (int) $minutes,
's' => (int) $seconds,
);
return $obj;
}
From: Convert seconds into days, hours, minutes and seconds
This function my be useful, you could extend it:
function formatSeconds($seconds) {
if(!is_integer($seconds)) {
return FALSE;
}
$fmt = "";
$days = floor($seconds / 86400);
if($days) {
$fmt .= $days."D ";
$seconds %= 86400;
}
$hours = floor($seconds / 3600);
if($hours) {
$fmt .= str_pad($hours, 2, '0', STR_PAD_LEFT).":";
$seconds %= 3600;
}
$mins = floor($seconds / 60 );
if($mins) {
$fmt .= str_pad($mins, 2, '0', STR_PAD_LEFT).":";
$seconds %= 60;
}
$fmt .= str_pad($seconds, 2, '0', STR_PAD_LEFT);
return $fmt;}
Try this:
date("H:i:s",-57600 + 685);
Taken from
http://bytes.com/topic/php/answers/3917-seconds-converted-hh-mm-ss
The gmtdate() function didn't work for me as I was tracking hours worked on a project and if it's over 24 hours, you get amount left over after 24 hours is subtracted. In other words 37 hours becomes 13 hours. (all as stated above by Glavic - thanks for your examples!)
This one worked well:
Convert seconds to format by 'foot' no limit :
$seconds = 8525;
$H = floor($seconds / 3600);
$i = ($seconds / 60) % 60;
$s = $seconds % 60;
echo sprintf("%02d:%02d:%02d", $H, $i, $s);
# 02:22:05
Solution from: https://gist.github.com/SteveJobzniak/c91a8e2426bac5cb9b0cbc1bdbc45e4b
This code avoids the tedious function calls and piece-by-piece string-building as much as possible, and the big and bulky functions people are making for this.
It returns an output in the format "1h05m00s" and uses leading zeroes for minutes and seconds, as long as another non-zero time component precedes them.
It also skips all empty leading components to avoid giving you useless info like "0h00m01s" (instead that will show up as "1s").
Example results: "1s", "1m00s", "19m08s", "1h00m00s", "4h08m39s".
$duration = 1; // values 0 and higher are supported!
$converted = [
'hours' => floor( $duration / 3600 ),
'minutes' => floor( ( $duration / 60 ) % 60 ),
'seconds' => ( $duration % 60 )
];
$result = ltrim( sprintf( '%02dh%02dm%02ds', $converted['hours'], $converted['minutes'], $converted['seconds'] ), '0hm' );
if( $result == 's' ) { $result = '0s'; }
If you want to make the code even shorter (but less readable), you can avoid the $converted array and instead put the values directly in the sprintf() call, as follows:
$duration = 1; // values 0 and higher are supported!
$result = ltrim( sprintf( '%02dh%02dm%02ds', floor( $duration / 3600 ), floor( ( $duration / 60 ) % 60 ), ( $duration % 60 ) ), '0hm' );
if( $result == 's' ) { $result = '0s'; }
Duration must be 0 or higher in both of the code pieces above. Negative durations are not supported. But you can handle negative durations by using the following alternative code instead:
$duration = -493; // negative values are supported!
$wasNegative = FALSE;
if( $duration < 0 ) { $wasNegative = TRUE; $duration = abs( $duration ); }
$converted = [
'hours' => floor( $duration / 3600 ),
'minutes' => floor( ( $duration / 60 ) % 60 ),
'seconds' => ( $duration % 60 )
];
$result = ltrim( sprintf( '%02dh%02dm%02ds', $converted['hours'], $converted['minutes'], $converted['seconds'] ), '0hm' );
if( $result == 's' ) { $result = '0s'; }
if( $wasNegative ) { $result = "-{$result}"; }
// $result is now "-8m13s"
Not sure why this hasn't been proposed yet, but here's a variation using DateInterval, which has the advantage that seconds > 86400 are not a problem (just don't expect the hours to be < 24)
noteable: the function returns the DateInterval object, so output format is up to the caller
function seconds2interval($seconds) {
$s = intval($seconds);
$hrs = floor($s / 3600);
$min = floor(($s - ($hrs * 3600)) / 60);
$sec = $s % 60;
$duration = sprintf('PT%dH%dM%dS', $hrs, $min, $sec);
$d = new DateInterval($duration);
return $d;
}
$d = seconds2interval(93837.3113);
echo $d->format('%H:%I:%s'); // 26:03:57
Just another method, with arithmetic operator Modulo (%). Easy read and understanding.
function readableSeconds($seconds)
{
$days = intdiv($seconds, 86400);
$hours = intdiv(($seconds % 86400), 3600);
$minutes = intdiv(($seconds % 3600), 60);
$seconds = $seconds % 60;
return ltrim(sprintf('%dd %dh %dm %ds', $days, $hours, $minutes, $seconds), ' 0dhm');
}
Output example: 1d 1h 8m 20s
A simple way to use DateTime for this is:
$time = 60; //sec.
$now = time();
$rep = new DateTime('#'.$now);
$diff = new DateTime('#'.($now+$time));
$return = $diff->diff($rep)->format($format);
//output: 01:04:65
It's a simple solution wich gives you the ability to use the format Method of DateTime.
In java you can use this way.
private String getHmaa(long seconds) {
String string;
int hours = (int) seconds / 3600;
int remainder = (int) seconds - hours * 3600;
int mins = remainder / 60;
//remainder = remainder - mins * 60;
//int secs = remainder;
if (hours < 12 && hours > 0) {
if (mins < 10) {
string = String.valueOf((hours < 10 ? "0" + hours : hours) + ":" + (mins > 0 ? "0" + mins : "0") + " AM");
} else {
string = String.valueOf((hours < 10 ? "0" + hours : hours) + ":" + (mins > 0 ? mins : "0") + " AM");
}
} else if (hours >= 12) {
if (mins < 10) {
string = String.valueOf(((hours - 12) < 10 ? "0" + (hours - 12) : ((hours - 12) == 12 ? "0" : (hours - 12))) + ":" + (mins > 0 ? "0" + mins : "0") + ((hours - 12) == 12 ? " AM" : " PM"));
} else {
string = String.valueOf(((hours - 12) < 10 ? "0" + (hours - 12) : ((hours - 12) == 12 ? "0" : (hours - 12))) + ":" + (mins > 0 ? mins : "0") + ((hours - 12) == 12 ? " AM" : " PM"));
}
} else {
if (mins < 10) {
string = String.valueOf("0" + ":" + (mins > 0 ? "0" + mins : "0") + " AM");
} else {
string = String.valueOf("0" + ":" + (mins > 0 ? mins : "0") + " AM");
}
}
return string;
}
If you want to create a audio/video duration string like YouTube, etc. you can do:
($seconds >= 60) ? ltrim(gmdate("H:i:s", $seconds), ":0") : gmdate("0:s", $seconds)
Will return strings like:
55.55 => '0:55'
100 => '1:40'
Probably won't work well for time >= 24 hours.
function timeToSecond($time){
$time_parts=explode(":",$time);
$seconds= ($time_parts[0]*86400) + ($time_parts[1]*3600) + ($time_parts[2]*60) + $time_parts[3] ;
return $seconds;
}
function secondToTime($time){
$seconds = $time % 60;
$seconds<10 ? "0".$seconds : $seconds;
if($seconds<10) {
$seconds="0".$seconds;
}
$time = ($time - $seconds) / 60;
$minutes = $time % 60;
if($minutes<10) {
$minutes="0".$minutes;
}
$time = ($time - $minutes) / 60;
$hours = $time % 24;
if($hours<10) {
$hours="0".$hours;
}
$days = ($time - $hours) / 24;
if($days<10) {
$days="0".$days;
}
$time_arr = array($days,$hours,$minutes,$seconds);
return implode(":",$time_arr);
}
Well I needed something that would reduce seconds into hours minutes and seconds, but would exceed 24 hours, and not reduce further down into days.
Here is a simple function that works. You can probably improve it... But here it is:
function formatSeconds($seconds)
{
$hours = 0;$minutes = 0;
while($seconds >= 60){$seconds -= 60;$minutes++;}
while($minutes >= 60){$minutes -=60;$hours++;}
$hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
$minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
$seconds = str_pad($seconds, 2, '0', STR_PAD_LEFT);
return $hours.":".$minutes.":".$seconds;
}
$given = 685;
/*
* In case $given == 86400, gmdate( "H" ) will convert it into '00' i.e. midnight.
* We would need to take this into consideration, and so we will first
* check the ratio of the seconds i.e. $given:$number_of_sec_in_a_day
* and then after multiplying it by the number of hours in a day (24), we
* will just use "floor" to get the number of hours as the rest would
* be the minutes and seconds anyways.
*
* We can also have minutes and seconds combined in one variable,
* e.g. $min_sec = gmdate( "i:s", $given );
* But for versatility sake, I have taken them separately.
*/
$hours = ( $given > 86399 ) ? '0'.floor( ( $given / 86400 ) * 24 )-gmdate( "H", $given ) : gmdate("H", $given );
$min = gmdate( "i", $given );
$sec = gmdate( "s", $given );
echo $formatted_string = $hours.':'.$min.':'.$sec;
To convert it into a function:
function getHoursFormat( $given ){
$hours = ( $given > 86399 ) ? '0'.floor( ( $given / 86400 ) * 24 )-gmdate( "H", $given ) : gmdate("H", $given );
$min = gmdate( "i", $given );
$sec = gmdate( "s", $given );
$formatted_string = $hours.':'.$min.':'.$sec;
return $formatted_string;
}
If you need to do that in javascript, you can do it in just one line of code as answered here Convert seconds to HH-MM-SS with JavaScript. Replace SECONDS with what you want to convert.
var time = new Date(SECONDS * 1000).toISOString().substr(11, 8);
This is a pretty way to do that:
function time_converter($sec_time, $format='h:m:s'){
$hour = intval($sec_time / 3600) >= 10 ? intval($sec_time / 3600) : '0'.intval($sec_time / 3600);
$minute = intval(($sec_time % 3600) / 60) >= 10 ? intval(($sec_time % 3600) / 60) : '0'.intval(($sec_time % 3600) / 60);
$sec = intval(($sec_time % 3600) % 60) >= 10 ? intval(($sec_time % 3600) % 60) : '0'.intval(($sec_time % 3600) % 60);
$format = str_replace('h', $hour, $format);
$format = str_replace('m', $minute, $format);
$format = str_replace('s', $sec, $format);
return $format;
}
The following codes can display total hours plus minutes and seconds accurately
$duration_in_seconds = 86401;
if($duration_in_seconds>0)
{
echo floor($duration_in_seconds/3600).gmdate(":i:s", $duration_in_seconds%3600);
}
else
{
echo "00:00:00";
}
Just in case anyone else is looking for a simple function to return this nicely formatted (I know it is not the format the OP asked for), this is what I've just come up with. Thanks to #mughal for the code this was based on.
function format_timer_result($time_in_seconds){
$time_in_seconds = ceil($time_in_seconds);
// Check for 0
if ($time_in_seconds == 0){
return 'Less than a second';
}
// Days
$days = floor($time_in_seconds / (60 * 60 * 24));
$time_in_seconds -= $days * (60 * 60 * 24);
// Hours
$hours = floor($time_in_seconds / (60 * 60));
$time_in_seconds -= $hours * (60 * 60);
// Minutes
$minutes = floor($time_in_seconds / 60);
$time_in_seconds -= $minutes * 60;
// Seconds
$seconds = floor($time_in_seconds);
// Format for return
$return = '';
if ($days > 0){
$return .= $days . ' day' . ($days == 1 ? '' : 's'). ' ';
}
if ($hours > 0){
$return .= $hours . ' hour' . ($hours == 1 ? '' : 's') . ' ';
}
if ($minutes > 0){
$return .= $minutes . ' minute' . ($minutes == 1 ? '' : 's') . ' ';
}
if ($seconds > 0){
$return .= $seconds . ' second' . ($seconds == 1 ? '' : 's') . ' ';
}
$return = trim($return);
return $return;
}
Anyone whose looking for this in the future, this gives the format the initial poster asked for.
$init = 685;
$hours = floor($init / 3600);
$hrlength=strlen($hours);
if ($hrlength==1) {$hrs="0".$hours;}
else {$hrs=$hours;}
$minutes = floor(($init / 60) % 60);
$minlength=strlen($minutes);
if ($minlength==1) {$mins="0".$minutes;}
else {$mins=$minutes;}
$seconds = $init % 60;
$seclength=strlen($seconds);
if ($seclength==1) {$secs="0".$seconds;}
else {$secs=$seconds;}
echo "$hrs:$mins:$secs";
<?php
$time=3*3600 + 30*60;
$year=floor($time/(365*24*60*60));
$time-=$year*(365*24*60*60);
$month=floor($time/(30*24*60*60));
$time-=$month*(30*24*60*60);
$day=floor($time/(24*60*60));
$time-=$day*(24*60*60);
$hour=floor($time/(60*60));
$time-=$hour*(60*60);
$minute=floor($time/(60));
$time-=$minute*(60);
$second=floor($time);
$time-=$second;
if($year>0){
echo $year." year, ";
}
if($month>0){
echo $month." month, ";
}
if($day>0){
echo $day." day, ";
}
if($hour>0){
echo $hour." hour, ";
}
if($minute>0){
echo $minute." minute, ";
}
if($second>0){
echo $second." second, ";
}
I have two timestamps and i would lime to get the difference based on
if its more that 60 seconds get in minutes
If more than 60 min get difference in hours
In my code i have
$diff = ($truckHistory->created_at - $model->created_at);
return $diff
The above returns in seconds
SO i have tried
$diff = ($truckHistory->created_at - $model->created_at);
return $this->convertToSecMinHour($diff)
public function convertToSecMinHour($diff){
switch($diff){
case ($diff <= 60):{
return $diff. "sec"
break;
}
//stuck for minutes and hours cases
}
}
I have this function that does just that, but it includes other methods of gauging time. You can simply remove those you do not need.
public function timeAgo($timestamp) {
$estimateTime = time() - $timestamp;
if ($estimateTime < 1) {
return 'less than 1 second ago';
}
$condition = array(
12 * 30 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($condition as $secs => $str) {
$d = $estimateTime / $secs;
if($d >= 1) {
$r = round( $d );
return $r . ' ' . $str . ( $r > 1 ? 's' : '' ) . ' ago';
}
}
}
You can get quickly using this function just passed the seconds to it. Example here
$time1 = '1504802148'; // Unix timeStamp
$timeDiff = ceil((time() - $time1));
echo secondsToTime($timeDiff);
function secondsToTime($seconds) {
$dtF = new \DateTime('#0');
$dtT = new \DateTime("#$seconds");
$makeTime = $dtF->diff($dtT)->format('%ad,%hh,%im,%ss');
$data = explode(",", $makeTime);
$array = array('0d', '0h', '0m');
$time = array_diff($data, $array);
return implode("", $time);
}
Use this function:
<?php
$diff = (time() - time()+60);
$diff2 = (time() - time()+2000);
$diff3 = (time() - time()+5000);
echo convertToSecMinHour($diff)."<br>";
echo convertToSecMinHour($diff2)."<br>";
echo convertToSecMinHour($diff3)."<br>";
function convertToSecMinHour($diff, $decimals = 2) {
switch($diff){
case ($diff <= 60):
$result = $diff;
$unit = "sec";
break;
case ($diff > 60 && $diff < 3600):
$result = ($diff / 60);
$unit = "min";
break;
case ($diff >= 3600):
$result = ($diff / (60 * 60));
$unit = "hrs";
break;
default:
$result = 0;
$unit = "";
}
return round($result, $decimals).$unit;
}
It'll return difference in seconds (i.e. 20 sec) if difference is less than 60, difference in minutes (i.e. 20 min) if difference is between 60 and 3600 seconds, and difference in hours (i.e. 20 hrs) if difference is larger than 3600. The second parameters is for number of decimals you want in the result (by default, 2).
Demo
I think you want $result and also you have other variables to use
$result;
$hour = $diff / 3600;
if ($hour == 0) {
$min = ($diff % 3600) / 60;
if ($min == 0) {
$sec = ($diff % 3600) % 60;
$result = $sec;
}else{
$result = $min;
}
}else{
$result = $hour;
}
I have a MySql datetime value like "2012-04-17 20:48:29". I want to convert this to a simple text like "10 days ago". I want to do this in either php or javascript! I tried to create my own algorithm to do this. But is there an already available solution for doing this?
you could use this pattern
$date = "2012-04-17 20:48:29";
$seconds = time() - strtotime($date);
$days = floor($seconds / 86400);
$seconds -= $days * 86400;
$hours = floor($seconds / 3600);
$seconds -= $hours * 3600;
$minutes = floor($seconds / 60);
$seconds -= $minutes * 60;
echo "$days days, $hours hours, $minutes minutes, $seconds seconds ago";
you should of course add some conditions before echoing the result. to only show 1 minute ago, or 3 hours ago, or 10 days ago...
With this function you'll get outputs like:
1 minute
5 minutes
15 hours
4 days
2 months
1.5 years
function time_ago_in_words($time) {
$from_time = strtotime($time);
$to_time = strtotime(gmd());
$distance_in_minutes = round((($to_time - $from_time))/60);
if ($distance_in_minutes < 0)
return (string)$distance_in_minutes.'E';
if (between($distance_in_minutes, 0, 1))
return '1 minute';
elseif (between($distance_in_minutes, 2, 44))
return $distance_in_minutes.' minutes';
elseif (between($distance_in_minutes, 45, 89))
return '1 hour';
elseif (between($distance_in_minutes, 90, 1439))
return round($distance_in_minutes/60).' hours';
elseif (between($distance_in_minutes, 1440, 2879))
return '1 day';
elseif (between($distance_in_minutes, 2880, 43199))
return round($distance_in_minutes/1440).' days';
elseif (between($distance_in_minutes, 43200, 86399))
return '1 month';
elseif (between($distance_in_minutes, 86400, 525959))
return round($distance_in_minutes/43200).' months';
elseif ($distance_in_minutes > 525959)
return number_format(round(($distance_in_minutes/525960), 1), 1).' years';
}
So you could do:
// Last time you logged in: 15 days ago.
Last time you logged in: <?php echo time_ago_in_words($user['last_logged_in']) ?> ago.
// We haven't seen you for 15 days!
We haven't seen you for <?php echo time_ago_in_words($user['last_logged_in']) ?>!
With PHP, you can call strftime to get different out put. Look here for more details.
There is also a jQuery plugin that you might look at as well: jQuery-dateFormat
Have fun!
I use this function:
function duration($integer)
{
$seconds=$integer;
$minutes = 0;
$hours = 0;
$days = 0;
$weeks = 0;
$return = "";
if ($seconds/60 >=1)
{
$minutes=floor($seconds/60);
if ($minutes/60 >= 1)
{ # Hours
$hours=floor($minutes/60);
if ($hours/24 >= 1)
{ #days
$days=floor($hours/24);
if ($days/7 >=1)
{ #weeks
$weeks=floor($days/7);
if ($weeks>=2) $return="$weeks Weeks";
else $return="$weeks Week";
} #end of weeks
$days=$days-(floor($days/7))*7;
if ($weeks>=1 && $days >=1) $return="$return, ";
if ($days >=2) $return="$return $days days";
if ($days ==1) $return="$return $days day";
} #end of days
$hours=$hours-(floor($hours/24))*24;
if ($days>=1 && $hours >=1) $return="$return, ";
if ($hours >=2) $return="$return $hours hours";
if ($hours ==1) $return="$return $hours hour";
} #end of Hours
$minutes=$minutes-(floor($minutes/60))*60;
if ($hours>=1 && $minutes >=1) $return="$return, ";
if ($minutes >=2) $return="$return $minutes minutes";
if ($minutes ==1) $return="$return $minutes minute";
} #end of minutes
$seconds=$integer-(floor($integer/60))*60;
if ($minutes>=1 && $seconds >=1) $return="$return, ";
if ($seconds >=2) $return="$return $seconds seconds";
if ($seconds ==1) $return="$return $seconds second";
$return="$return.";
return $return;
}
echo duration(time() - strtotime($date));
Outputting from a directions api I have a duration it will take the user to get from a to b. At the moment it is minutes but if the users journey will take 3 hours and 20 minutes it will output 200 minutes.
I would like it to work out that that is greater than 60 minutes. then divide by 60 and add the remainder to give
3 hours 20 minutes.
How do we do this.
Marvellous
with php >= 5.3.0 you could do that :
$dt = new DateTime();
$dt->add(new DateInterval('PT200M'));
$interval = $dt->diff(new DateTime());
echo $interval->format('%Hh %Im %Ss');
Output (on my locale) : 02h 40m 00s
source : http://php.net/manual/en/class.dateinterval.php
function getNiceDuration($durationInSeconds) {
$duration = '';
$days = floor($durationInSeconds / 86400);
$durationInSeconds -= $days * 86400;
$hours = floor($durationInSeconds / 3600);
$durationInSeconds -= $hours * 3600;
$minutes = floor($durationInSeconds / 60);
$seconds = $durationInSeconds - $minutes * 60;
if($days > 0) {
$duration .= $days . ' days';
}
if($hours > 0) {
$duration .= ' ' . $hours . ' hours';
}
if($minutes > 0) {
$duration .= ' ' . $minutes . ' minutes';
}
if($seconds > 0) {
$duration .= ' ' . $seconds . ' seconds';
}
return $duration;
}
In case you have duration in seconds, you can format it with PHP gmdate() function:
echo gmdate("H:i:s", $seconds);
(Note: works for durations up to 24 hours)
$minutes = 200;
if ($minutes >= 60)
{
$hours = (int)($minutes / 60);
$minutes = $minutes % 60;
}
<?php
$time = 200; // minutes
if ($time > 60) {
$minutes = $time % 60;
$hours = ($time - $minutes) / 60;
}
echo "$hours hours $minutes minutes";
?>
Use modulo division :)
function format_minutes($value)
{
$hours = intval($value / 60);
$minutes = $value % 60;
if ($hours != 0) {
$str = $hours . ' hour';
// Handle pluralisation.
if (abs($hours) != 1) {
$str .= 's';
}
}
// Always show minutes if there are no hours.
if ($minutes != 0 || $hours == 0) {
$str .= ' ' . $minutes . ' minute';
// Handle pluralisation.
if (abs($minutes) != 1) {
$str .= 's';
}
}
// There will be a leading space if hours is zero.
return trim($str);
}
Thanks for the function. I needed to change it to make it work better:
The minutes were over 60:
$seconds = $secs % 60;
$hours = floor($secs / 3600);
$secs = $secs - $hours*3600;
$minutes = floor($secs / 60);
Best
For those who need it... Minutes to Period of Time - PT:
<?php
function pttime($time, $format)
{
if ($time < 1) {
return;
}
$hours = floor($time / 60);
$minutes = ($time % 60);
//is PT
if ($format == 'PT') {
//full hour
if (($hours > 0) && ($minutes == 0)) {
$time_result = 'PT' . $hours . 'H';
}
//hour and minutes
if (($hours > 0) && ($minutes <> 0)) {
$time_result = 'PT' . $hours . 'H' . $minutes . 'M';
}
//just minutes
if ($hours == 0) {
$time_result = 'PT' . $minutes . 'M';
}
}
//it's not PT
else {
$time_result = sprintf("%02s", $hours) . ':' . sprintf("%02s", $minutes);
}
return $time_result;
}
//input in minutes and its outputs
echo pttime(155,'PT'); //output -> PT2H35M
echo pttime(52,'PT'); //output -> PT52M
echo pttime(60,'PT'); //output -> PT1H
echo pttime(60,''); //output -> 01:00
A simple duration-to-formatted-time example (with the duration given in seconds, and the output formatted as [##:]##:##):
public function format_duration($secs, $delimiter = ':')
{
$seconds = $secs % 60;
$minutes = floor($secs / 60);
$hours = floor($secs / 3600);
$seconds = str_pad($seconds, 2, "0", STR_PAD_LEFT);
$minutes = str_pad($minutes, 2, "0", STR_PAD_LEFT).$delimiter;
$hours = ($hours > 0) ? str_pad($hours, 2, "0", STR_PAD_LEFT).$delimiter : '';
return "$hours$minutes$seconds";
}
I need to convert seconds to "Hour:Minute:Second".
For example: "685" converted to "00:11:25"
How can I achieve this?
You can use the gmdate() function:
echo gmdate("H:i:s", 685);
One hour is 3600sec, one minute is 60sec so why not:
<?php
$init = 685;
$hours = floor($init / 3600);
$minutes = floor(($init / 60) % 60);
$seconds = $init % 60;
echo "$hours:$minutes:$seconds";
?>
which produces:
$ php file.php
0:11:25
(I've not tested this much, so there might be errors with floor or so)
here you go
function format_time($t,$f=':') // t = seconds, f = separator
{
return sprintf("%02d%s%02d%s%02d", floor($t/3600), $f, ($t/60)%60, $f, $t%60);
}
echo format_time(685); // 00:11:25
Use function gmdate() only if seconds are less than 86400 (1 day) :
$seconds = 8525;
echo gmdate('H:i:s', $seconds);
# 02:22:05
See: gmdate()
Run the Demo
Convert seconds to format by 'foot' no limit* :
$seconds = 8525;
$H = floor($seconds / 3600);
$i = ($seconds / 60) % 60;
$s = $seconds % 60;
echo sprintf("%02d:%02d:%02d", $H, $i, $s);
# 02:22:05
See: floor(), sprintf(), arithmetic operators
Run the Demo
Example use of DateTime extension:
$seconds = 8525;
$zero = new DateTime("#0");
$offset = new DateTime("#$seconds");
$diff = $zero->diff($offset);
echo sprintf("%02d:%02d:%02d", $diff->days * 24 + $diff->h, $diff->i, $diff->s);
# 02:22:05
See: DateTime::__construct(), DateTime::modify(), clone,
sprintf()
Run the Demo
MySQL example range of the result is constrained to that of the TIME data type, which is from -838:59:59 to 838:59:59 :
SELECT SEC_TO_TIME(8525);
# 02:22:05
See: SEC_TO_TIME
Run the Demo
PostgreSQL example:
SELECT TO_CHAR('8525 second'::interval, 'HH24:MI:SS');
# 02:22:05
Run the Demo
Other solutions use gmdate, but fail in edge cases where you have more than 86400 seconds. To get around this, we can simply compute the number of hours ourselves, then let gmdate compute the remaining seconds into minutes/seconds.
echo floor($seconds / 3600) . gmdate(":i:s", $seconds % 3600);
Input: 6030
Output: 1:40:30
Input: 2000006030
Output: 555557:13:50
// TEST
// 1 Day 6 Hours 50 Minutes 31 Seconds ~ 111031 seconds
$time = 111031; // time duration in seconds
$days = floor($time / (60 * 60 * 24));
$time -= $days * (60 * 60 * 24);
$hours = floor($time / (60 * 60));
$time -= $hours * (60 * 60);
$minutes = floor($time / 60);
$time -= $minutes * 60;
$seconds = floor($time);
$time -= $seconds;
echo "{$days}d {$hours}h {$minutes}m {$seconds}s"; // 1d 6h 50m 31s
If you don't like accepted answer or popular ones, then try this one
function secondsToTime($seconds_time)
{
if ($seconds_time < 24 * 60 * 60) {
return gmdate('H:i:s', $seconds_time);
} else {
$hours = floor($seconds_time / 3600);
$minutes = floor(($seconds_time - $hours * 3600) / 60);
$seconds = floor($seconds_time - ($hours * 3600) - ($minutes * 60));
return "$hours:$minutes:$seconds";
}
}
secondsToTime(108620); // 30:10:20
gmdate("H:i:s", no_of_seconds);
Will not give time in H:i:s format if no_of_seconds is greater than 1 day (seconds in a day).
It will neglect day value and give only Hour:Min:Seconds
For example:
gmdate("H:i:s", 89922); // returns 0:58:42 not (1 Day 0:58:42) or 24:58:42
Here is a one liner that handles negative seconds and more than 1 day worth of seconds.
sprintf("%s:%'02s:%'02s\n", intval($seconds/60/60), abs(intval(($seconds%3600) / 60)), abs($seconds%60));
For Example:
$seconds= -24*60*60 - 2*60*60 - 3*60 - 4; // minus 1 day 2 hours 3 minutes 4 seconds
echo sprintf("%s:%'02s:%'02s\n", intval($seconds/60/60), abs(intval(($seconds%3600) / 60)), abs($seconds%60));
outputs: -26:03:04
I have already explained this here
pasting that answer here as well
For till 23:59:59 hours you can use PHP default function
echo gmdate("H:i:s", 86399);
Which will only return the result till 23:59:59
If your seconds is more than 86399 than
with the help of #VolkerK answer
$time = round($seconds);
echo sprintf('%02d:%02d:%02d', ($time/3600),($time/60%60), $time%60);
will be the best options to use ...
write function like this to return an array
function secondsToTime($seconds) {
// extract hours
$hours = floor($seconds / (60 * 60));
// extract minutes
$divisor_for_minutes = $seconds % (60 * 60);
$minutes = floor($divisor_for_minutes / 60);
// extract the remaining seconds
$divisor_for_seconds = $divisor_for_minutes % 60;
$seconds = ceil($divisor_for_seconds);
// return the final array
$obj = array(
"h" => (int) $hours,
"m" => (int) $minutes,
"s" => (int) $seconds,
);
return $obj;
}
then simply call the function like this:
secondsToTime(100);
output is
Array ( [h] => 0 [m] => 1 [s] => 40 )
See:
/**
* Convert number of seconds into hours, minutes and seconds
* and return an array containing those values
*
* #param integer $inputSeconds Number of seconds to parse
* #return array
*/
function secondsToTime($inputSeconds) {
$secondsInAMinute = 60;
$secondsInAnHour = 60 * $secondsInAMinute;
$secondsInADay = 24 * $secondsInAnHour;
// extract days
$days = floor($inputSeconds / $secondsInADay);
// extract hours
$hourSeconds = $inputSeconds % $secondsInADay;
$hours = floor($hourSeconds / $secondsInAnHour);
// extract minutes
$minuteSeconds = $hourSeconds % $secondsInAnHour;
$minutes = floor($minuteSeconds / $secondsInAMinute);
// extract the remaining seconds
$remainingSeconds = $minuteSeconds % $secondsInAMinute;
$seconds = ceil($remainingSeconds);
// return the final array
$obj = array(
'd' => (int) $days,
'h' => (int) $hours,
'm' => (int) $minutes,
's' => (int) $seconds,
);
return $obj;
}
From: Convert seconds into days, hours, minutes and seconds
This function my be useful, you could extend it:
function formatSeconds($seconds) {
if(!is_integer($seconds)) {
return FALSE;
}
$fmt = "";
$days = floor($seconds / 86400);
if($days) {
$fmt .= $days."D ";
$seconds %= 86400;
}
$hours = floor($seconds / 3600);
if($hours) {
$fmt .= str_pad($hours, 2, '0', STR_PAD_LEFT).":";
$seconds %= 3600;
}
$mins = floor($seconds / 60 );
if($mins) {
$fmt .= str_pad($mins, 2, '0', STR_PAD_LEFT).":";
$seconds %= 60;
}
$fmt .= str_pad($seconds, 2, '0', STR_PAD_LEFT);
return $fmt;}
Try this:
date("H:i:s",-57600 + 685);
Taken from
http://bytes.com/topic/php/answers/3917-seconds-converted-hh-mm-ss
The gmtdate() function didn't work for me as I was tracking hours worked on a project and if it's over 24 hours, you get amount left over after 24 hours is subtracted. In other words 37 hours becomes 13 hours. (all as stated above by Glavic - thanks for your examples!)
This one worked well:
Convert seconds to format by 'foot' no limit :
$seconds = 8525;
$H = floor($seconds / 3600);
$i = ($seconds / 60) % 60;
$s = $seconds % 60;
echo sprintf("%02d:%02d:%02d", $H, $i, $s);
# 02:22:05
Solution from: https://gist.github.com/SteveJobzniak/c91a8e2426bac5cb9b0cbc1bdbc45e4b
This code avoids the tedious function calls and piece-by-piece string-building as much as possible, and the big and bulky functions people are making for this.
It returns an output in the format "1h05m00s" and uses leading zeroes for minutes and seconds, as long as another non-zero time component precedes them.
It also skips all empty leading components to avoid giving you useless info like "0h00m01s" (instead that will show up as "1s").
Example results: "1s", "1m00s", "19m08s", "1h00m00s", "4h08m39s".
$duration = 1; // values 0 and higher are supported!
$converted = [
'hours' => floor( $duration / 3600 ),
'minutes' => floor( ( $duration / 60 ) % 60 ),
'seconds' => ( $duration % 60 )
];
$result = ltrim( sprintf( '%02dh%02dm%02ds', $converted['hours'], $converted['minutes'], $converted['seconds'] ), '0hm' );
if( $result == 's' ) { $result = '0s'; }
If you want to make the code even shorter (but less readable), you can avoid the $converted array and instead put the values directly in the sprintf() call, as follows:
$duration = 1; // values 0 and higher are supported!
$result = ltrim( sprintf( '%02dh%02dm%02ds', floor( $duration / 3600 ), floor( ( $duration / 60 ) % 60 ), ( $duration % 60 ) ), '0hm' );
if( $result == 's' ) { $result = '0s'; }
Duration must be 0 or higher in both of the code pieces above. Negative durations are not supported. But you can handle negative durations by using the following alternative code instead:
$duration = -493; // negative values are supported!
$wasNegative = FALSE;
if( $duration < 0 ) { $wasNegative = TRUE; $duration = abs( $duration ); }
$converted = [
'hours' => floor( $duration / 3600 ),
'minutes' => floor( ( $duration / 60 ) % 60 ),
'seconds' => ( $duration % 60 )
];
$result = ltrim( sprintf( '%02dh%02dm%02ds', $converted['hours'], $converted['minutes'], $converted['seconds'] ), '0hm' );
if( $result == 's' ) { $result = '0s'; }
if( $wasNegative ) { $result = "-{$result}"; }
// $result is now "-8m13s"
Not sure why this hasn't been proposed yet, but here's a variation using DateInterval, which has the advantage that seconds > 86400 are not a problem (just don't expect the hours to be < 24)
noteable: the function returns the DateInterval object, so output format is up to the caller
function seconds2interval($seconds) {
$s = intval($seconds);
$hrs = floor($s / 3600);
$min = floor(($s - ($hrs * 3600)) / 60);
$sec = $s % 60;
$duration = sprintf('PT%dH%dM%dS', $hrs, $min, $sec);
$d = new DateInterval($duration);
return $d;
}
$d = seconds2interval(93837.3113);
echo $d->format('%H:%I:%s'); // 26:03:57
Just another method, with arithmetic operator Modulo (%). Easy read and understanding.
function readableSeconds($seconds)
{
$days = intdiv($seconds, 86400);
$hours = intdiv(($seconds % 86400), 3600);
$minutes = intdiv(($seconds % 3600), 60);
$seconds = $seconds % 60;
return ltrim(sprintf('%dd %dh %dm %ds', $days, $hours, $minutes, $seconds), ' 0dhm');
}
Output example: 1d 1h 8m 20s
A simple way to use DateTime for this is:
$time = 60; //sec.
$now = time();
$rep = new DateTime('#'.$now);
$diff = new DateTime('#'.($now+$time));
$return = $diff->diff($rep)->format($format);
//output: 01:04:65
It's a simple solution wich gives you the ability to use the format Method of DateTime.
In java you can use this way.
private String getHmaa(long seconds) {
String string;
int hours = (int) seconds / 3600;
int remainder = (int) seconds - hours * 3600;
int mins = remainder / 60;
//remainder = remainder - mins * 60;
//int secs = remainder;
if (hours < 12 && hours > 0) {
if (mins < 10) {
string = String.valueOf((hours < 10 ? "0" + hours : hours) + ":" + (mins > 0 ? "0" + mins : "0") + " AM");
} else {
string = String.valueOf((hours < 10 ? "0" + hours : hours) + ":" + (mins > 0 ? mins : "0") + " AM");
}
} else if (hours >= 12) {
if (mins < 10) {
string = String.valueOf(((hours - 12) < 10 ? "0" + (hours - 12) : ((hours - 12) == 12 ? "0" : (hours - 12))) + ":" + (mins > 0 ? "0" + mins : "0") + ((hours - 12) == 12 ? " AM" : " PM"));
} else {
string = String.valueOf(((hours - 12) < 10 ? "0" + (hours - 12) : ((hours - 12) == 12 ? "0" : (hours - 12))) + ":" + (mins > 0 ? mins : "0") + ((hours - 12) == 12 ? " AM" : " PM"));
}
} else {
if (mins < 10) {
string = String.valueOf("0" + ":" + (mins > 0 ? "0" + mins : "0") + " AM");
} else {
string = String.valueOf("0" + ":" + (mins > 0 ? mins : "0") + " AM");
}
}
return string;
}
If you want to create a audio/video duration string like YouTube, etc. you can do:
($seconds >= 60) ? ltrim(gmdate("H:i:s", $seconds), ":0") : gmdate("0:s", $seconds)
Will return strings like:
55.55 => '0:55'
100 => '1:40'
Probably won't work well for time >= 24 hours.
function timeToSecond($time){
$time_parts=explode(":",$time);
$seconds= ($time_parts[0]*86400) + ($time_parts[1]*3600) + ($time_parts[2]*60) + $time_parts[3] ;
return $seconds;
}
function secondToTime($time){
$seconds = $time % 60;
$seconds<10 ? "0".$seconds : $seconds;
if($seconds<10) {
$seconds="0".$seconds;
}
$time = ($time - $seconds) / 60;
$minutes = $time % 60;
if($minutes<10) {
$minutes="0".$minutes;
}
$time = ($time - $minutes) / 60;
$hours = $time % 24;
if($hours<10) {
$hours="0".$hours;
}
$days = ($time - $hours) / 24;
if($days<10) {
$days="0".$days;
}
$time_arr = array($days,$hours,$minutes,$seconds);
return implode(":",$time_arr);
}
Well I needed something that would reduce seconds into hours minutes and seconds, but would exceed 24 hours, and not reduce further down into days.
Here is a simple function that works. You can probably improve it... But here it is:
function formatSeconds($seconds)
{
$hours = 0;$minutes = 0;
while($seconds >= 60){$seconds -= 60;$minutes++;}
while($minutes >= 60){$minutes -=60;$hours++;}
$hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
$minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
$seconds = str_pad($seconds, 2, '0', STR_PAD_LEFT);
return $hours.":".$minutes.":".$seconds;
}
$given = 685;
/*
* In case $given == 86400, gmdate( "H" ) will convert it into '00' i.e. midnight.
* We would need to take this into consideration, and so we will first
* check the ratio of the seconds i.e. $given:$number_of_sec_in_a_day
* and then after multiplying it by the number of hours in a day (24), we
* will just use "floor" to get the number of hours as the rest would
* be the minutes and seconds anyways.
*
* We can also have minutes and seconds combined in one variable,
* e.g. $min_sec = gmdate( "i:s", $given );
* But for versatility sake, I have taken them separately.
*/
$hours = ( $given > 86399 ) ? '0'.floor( ( $given / 86400 ) * 24 )-gmdate( "H", $given ) : gmdate("H", $given );
$min = gmdate( "i", $given );
$sec = gmdate( "s", $given );
echo $formatted_string = $hours.':'.$min.':'.$sec;
To convert it into a function:
function getHoursFormat( $given ){
$hours = ( $given > 86399 ) ? '0'.floor( ( $given / 86400 ) * 24 )-gmdate( "H", $given ) : gmdate("H", $given );
$min = gmdate( "i", $given );
$sec = gmdate( "s", $given );
$formatted_string = $hours.':'.$min.':'.$sec;
return $formatted_string;
}
If you need to do that in javascript, you can do it in just one line of code as answered here Convert seconds to HH-MM-SS with JavaScript. Replace SECONDS with what you want to convert.
var time = new Date(SECONDS * 1000).toISOString().substr(11, 8);
This is a pretty way to do that:
function time_converter($sec_time, $format='h:m:s'){
$hour = intval($sec_time / 3600) >= 10 ? intval($sec_time / 3600) : '0'.intval($sec_time / 3600);
$minute = intval(($sec_time % 3600) / 60) >= 10 ? intval(($sec_time % 3600) / 60) : '0'.intval(($sec_time % 3600) / 60);
$sec = intval(($sec_time % 3600) % 60) >= 10 ? intval(($sec_time % 3600) % 60) : '0'.intval(($sec_time % 3600) % 60);
$format = str_replace('h', $hour, $format);
$format = str_replace('m', $minute, $format);
$format = str_replace('s', $sec, $format);
return $format;
}
The following codes can display total hours plus minutes and seconds accurately
$duration_in_seconds = 86401;
if($duration_in_seconds>0)
{
echo floor($duration_in_seconds/3600).gmdate(":i:s", $duration_in_seconds%3600);
}
else
{
echo "00:00:00";
}
Just in case anyone else is looking for a simple function to return this nicely formatted (I know it is not the format the OP asked for), this is what I've just come up with. Thanks to #mughal for the code this was based on.
function format_timer_result($time_in_seconds){
$time_in_seconds = ceil($time_in_seconds);
// Check for 0
if ($time_in_seconds == 0){
return 'Less than a second';
}
// Days
$days = floor($time_in_seconds / (60 * 60 * 24));
$time_in_seconds -= $days * (60 * 60 * 24);
// Hours
$hours = floor($time_in_seconds / (60 * 60));
$time_in_seconds -= $hours * (60 * 60);
// Minutes
$minutes = floor($time_in_seconds / 60);
$time_in_seconds -= $minutes * 60;
// Seconds
$seconds = floor($time_in_seconds);
// Format for return
$return = '';
if ($days > 0){
$return .= $days . ' day' . ($days == 1 ? '' : 's'). ' ';
}
if ($hours > 0){
$return .= $hours . ' hour' . ($hours == 1 ? '' : 's') . ' ';
}
if ($minutes > 0){
$return .= $minutes . ' minute' . ($minutes == 1 ? '' : 's') . ' ';
}
if ($seconds > 0){
$return .= $seconds . ' second' . ($seconds == 1 ? '' : 's') . ' ';
}
$return = trim($return);
return $return;
}
Anyone whose looking for this in the future, this gives the format the initial poster asked for.
$init = 685;
$hours = floor($init / 3600);
$hrlength=strlen($hours);
if ($hrlength==1) {$hrs="0".$hours;}
else {$hrs=$hours;}
$minutes = floor(($init / 60) % 60);
$minlength=strlen($minutes);
if ($minlength==1) {$mins="0".$minutes;}
else {$mins=$minutes;}
$seconds = $init % 60;
$seclength=strlen($seconds);
if ($seclength==1) {$secs="0".$seconds;}
else {$secs=$seconds;}
echo "$hrs:$mins:$secs";
<?php
$time=3*3600 + 30*60;
$year=floor($time/(365*24*60*60));
$time-=$year*(365*24*60*60);
$month=floor($time/(30*24*60*60));
$time-=$month*(30*24*60*60);
$day=floor($time/(24*60*60));
$time-=$day*(24*60*60);
$hour=floor($time/(60*60));
$time-=$hour*(60*60);
$minute=floor($time/(60));
$time-=$minute*(60);
$second=floor($time);
$time-=$second;
if($year>0){
echo $year." year, ";
}
if($month>0){
echo $month." month, ";
}
if($day>0){
echo $day." day, ";
}
if($hour>0){
echo $hour." hour, ";
}
if($minute>0){
echo $minute." minute, ";
}
if($second>0){
echo $second." second, ";
}