I need to convert seconds to \"Hour:Minute:Second\".
For example: \"685\" converted to \"00:11:25\"
How can I achieve this?
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