0

I know about the date and gmdate functions, but my needs are different in this case.

I have a number of seconds which I need to convert to something like:

A days B hours C minutes D seconds

I don't know how to format my seconds like this.

Any help would be appreciated.

aborted
  • 4,481
  • 14
  • 69
  • 132

2 Answers2

1

Just use floor and the values 86400 (seconds in a day - 60 * 60 * 24), 3600 (seconds in an hour - 60 * 60) and 60 (seconds in a minute):

<?php
    function secondsToTime($seconds) {
        $days = floor($seconds / 86400);
        $seconds -= ($days * 86400);

        $hours = floor($seconds / 3600);
        $seconds -= ($hours * 3600);

        $minutes = floor($seconds / 60);
        $seconds -= ($minutes * 60);

        $values = array(
            'day'    => $days,
            'hour'   => $hours,
            'minute' => $minutes,
            'second' => $seconds
        );

        $parts = array();

        foreach ($values as $text => $value) {
            if ($value > 0) {
                $parts[] = $value . ' ' . $text . ($value > 1 ? 's' : '');
            }
        }

        return implode(' ', $parts);
    }

    var_dump(secondsToTime(1234561));
    //string(36) "14 days 6 hours 56 minutes 1 second"
?>

DEMO

h2ooooooo
  • 39,111
  • 8
  • 68
  • 102
0

This can be achieved with Date and Time extension:

Use example:

echo secondsToTime(1234563);
# 14 days, 6 hours, 56 minutes and 3 seconds

Link to the function + Demo.

Community
  • 1
  • 1
Glavić
  • 42,781
  • 13
  • 77
  • 107