Convert seconds to Hour:Minute:Second
I need to convert seconds to «Hour:Minute:Second». For example: «685» converted to «00:11:25» How can I achieve this?
30 Answers 30
You can use the gmdate() function:
H represents the amount of hours in a single day. So if you have 90000 seconds and you’ll use H on it the result will be 01 (first hour of a next day). NOT 25 — there are only 24 hours in a day.
I’m not sure this is the right answer, this will produce a datetime . so if we expect result > 24 hours it will not work. Also if we need some negative result ( for example working with offset ) it will not work. -1 for the lark of details
This shouldn’t be the accepted answer due to the obvious flaw for times that are greater than 24 hours.
For use with days when numbers might be bigger than 85399 you can use echo gmdate(«z H:i:s», 685); z is the amount of days in the year starting with 0. You can obviously review the php date manual to cater to your specific needs.
One hour is 3600sec, one minute is 60sec so why not:
(I’ve not tested this much, so there might be errors with floor or so)
Good answer, but make sure you subtract $hours*3600 and $minutes*60 from $init in between each operation otherwise you’ll end up double counting minutes and seconds.
This one works best for me. One little thing to add. When you have less than 10 hours it shows 3:10:59. Make it look like the OP wants 03:10:59. Works like this $hours = floor( 2300 / 3600); return ($hours < 10 ? '0' . $hours : $hours) . gmdate(":i:s", $this->getSeconds() % 3600);
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
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
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
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
SELECT TO_CHAR('8525 second'::interval, 'HH24:MI:SS'); # 02:22:05
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: 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 "d h m 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
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
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));
$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));
I have already explained this here pasting that answer here as well
For till 23:59:59 hours you can use PHP default function
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:
/** * 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; >
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;>
Not entirely sure, but I’m pretty sure it’s setting the time to 0 and then anything on top of that would simply be the correct answer
This puts leading 0’s in front of the minutes, which you can’t adjust with date() — ca.php.net/manual/en/function.date.php
@barfoon — true, but I believe this is what M.Ezz was asking for, and it is a standard used in time. This looks strange from my experience «3:7:5» instead of «03:07:05», or even «3:7», looks more like a ratio to me.
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
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' )
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' )
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 is now "-8m13s"
PHP – сколько дней/часов/минут/секунд осталось до даты
Скрипт на пхп, который выводит оставшееся время до введенной даты.
Как на PHP рассчитать время до указанного события
/** * Счетчик обратного отсчета * * @param mixed $date * @return */ function downcounter($date) < $check_time = strtotime($date) - time(); if($check_time $days = floor($check_time/86400); $hours = floor(($check_time%86400)/3600); $minutes = floor(($check_time%3600)/60); $seconds = $check_time%60; $str = ''; if($days > 0) $str .= declension($days,array('день','дня','дней')).' '; if($hours > 0) $str .= declension($hours,array('час','часа','часов')).' '; if($minutes > 0) $str .= declension($minutes,array('минута','минуты','минут')).' '; if($seconds > 0) $str .= declension($seconds,array('секунда','секунды','секунд')); return $str; > /** * Функция склонения слов * * @param mixed $digit * @param mixed $expr * @param bool $onlyword * @return */ function declension($digit,$expr,$onlyword=false)< if(!is_array($expr)) $expr = array_filter(explode(' ', $expr)); if(empty($expr[2])) $expr[2]=$expr[1]; $i=preg_replace('/[^0-9]+/s','',$digit)%100; if($onlyword) $digit=''; if($i>=5 && $i<=20) $res=$digit.' '.$expr[2]; else < $i%=10; if($i==1) $res=$digit.' '.$expr[0]; elseif($i>=2 && $i <=4) $res=$digit.' '.$expr[1]; else $res=$digit.' '.$expr[2]; >return trim($res); >
- downcounter() – функция счетчика обратного отсчета
- declension() – вспомогательная функция, для склонения слов
Вводим дату события, которая обязательно должна быть больше текущей. Применять функцию подсчета даты можно так:
Как вы понимаете, вешать скрипт, который отправляет ajax запрос на сервер каждую секунду, не очень хорошо :). В следующих статьях вы узнаете как при помощи js показывать актуальное время.
Как проверить, сколько часов и минут осталось до.
Здравствуйте, у меня проблема: не могу просчитать, сколько часов и минут осталось до какого либо времени. Например, есть дата «14.12.2011 13:12» и мне нужно посчитать, сколько часов и минут до ее наступления осталось. Как это можно реализовать на PHP?
Diff — как узнать, сколько осталось дней, часов, минут, секунд ?
Здравствуйте! Подскажите пожалуйста, как при помощи diff узнать сколько осталось дней, часов.
Сколько лет, месяцев, дней, часов осталось до заданной даты
Нужно написать скрипт, вычисляющий сколько лет, месяцев, дней, часов осталось до заданной даты.
Определить сколько минут осталось (Относительно)
Здравствуйте, мне нужно: Определить сколько минут осталось относительно от минут. То есть к.
Как преобразовать число в количество часов и минут?
как можно преобразовать число (кол-во минут) в такой формат ЧЧ часов ММ минут, к примеру число 100.
Сообщение было отмечено Para bellum как решение
Решение
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
$met = "14.11.2011 13:12"; $metTS = strtotime($met); echo "Вы ввели время - " . strftime("%d-%m-%Y %H:%M", $metTS) . "
"; echo "Текущее время - " . strftime("%d-%m-%Y %H:%M") . "
"; $sub = $metTS - time(); if ($sub 0) { echo "\nУстановленная дата прошла
\n"; } elseif ($sub > 0) { echo "\nУстановленная дата впереди
\n"; } else { exit("\nУстановленно текущее время.
\n"); } $sub = abs($sub); $days = (int)($sub / (24*60*60)); $hours = (int)(($sub - $days * 24 * 60 * 60) / (60*60)); $min = (int)(($sub - $days * 24 * 60 *60 - $hours * 60 * 60) / 60); $sec = $sub - $days * 24 * 60 *60 - $hours * 60 * 60 - $min * 60; echo "суток - $days
\n"; echo "часов - $hours
\n"; echo "минут - $min
\n"; echo "секунд - $sec
\n"; ?>
Вообще вместо функции strtotime() мне кажется желательнее использовать функцию srtptime(). Но она у меня почему то отсутствует. Может гуру ответят почему? Поэтому я проверил введенное время в строке 4.