Skip to content

Instantly share code, notes, and snippets.

@marcelod
Last active July 27, 2022 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcelod/9e476cabb0513a49e43a8a711600cc1f to your computer and use it in GitHub Desktop.
Save marcelod/9e476cabb0513a49e43a8a711600cc1f to your computer and use it in GitHub Desktop.
Convert seconds to hours : minutes : seconds
<?php
function seconds_to_time($seconds)
{
$normalized = (int) ($seconds ?? 0);
if ($normalized === 0) {
return '00:00:00';
}
if ($normalized >= 86400) {
$hours = floor($normalized / 3600);
$minutes = ($normalized / 60) % 60;
$seconds = $normalized % 60;
$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;
}
return gmdate('H:i:s', $normalized);
}
// seconds_to_time(1) -- 00:00:01
// seconds_to_time(60) -- 00:01:00
// seconds_to_time(3600) -- 01:00:00
// seconds_to_time(86400) -- 24:00:00
// seconds_to_time(86401) -- 24:00:01
// seconds_to_time(86460) -- 24:01:00
// seconds_to_time(87000) -- 24:10:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment