17
timeformat
time_format
SYNOPSIS
time_format($n, $d=false)
DESCRIPTION
time_format returns the string representation of the number of seconds $n formatted in a compact form.
If $n is less than 60, $n is returned in seconds.
If $n is greater than or equal to 60 and less than 3600, $n is returned in minutes and seconds.
If $n is greater than or equal to 3600 and less than one day, $n is returned in hours, minutes and seconds.
If $n is greater than or equal to one day, if $d is false, $n is returned in hours, minutes and seconds, otherwise in days, hours, minutes and seconds using $d as the day suffix.
If $n is negative, time_format returns 0.
EXAMPLE
To format a number of seconds:
php > require 'library/timeformat.php';
php > echo time_format(12);
12s
php > echo time_format(123);
2m03s
php > echo time_format(12345);
3h25m45s
php > echo time_format(123456);
34h17m36s
php > echo time_format(123456, 'd');
1d10h17m36s
CODE
- function time_format($n, $d=false) {
- if ($n < 0) {
- return 0;
- }
- if ($n < 60) {
- return sprintf('%ds', $n);
- }
- if ($n < 3600) {
- return sprintf('%dm%02ds', intdiv($n, 60), $n % 60);
- }
- if ($n < 24*3600 or $d === false) {
- return sprintf('%dh%02dm%02ds', intdiv($n, 3600), intdiv($n, 60) % 60, $n % 60);
- }
- return sprintf('%d%s%02dh%02dm%02ds', intdiv($n, 24*3600), $d, intdiv($n, 3600) % 24, intdiv($n, 60) % 60, $n % 60);
- }
Comments