Skip to main content

This function will return the duration of the given time period in days, hours, minutes and seconds. Example: secondsToString(1234567) would return "14 days, 6 hours, 56 minutes, 7 seconds".

<?php

/**
 * Seconds to String
 *
 * This function will return the duration of the given time period in days,
 * hours, minutes and seconds.
 *
 * ex: secondsToString(1234567) would return: "14 days, 6 hours, 56 minutes, 7
 * seconds".
 *
 * @param integer $seconds Total time in seconds.
 *
 * @return string "1234567" would return "14 days, 6 hours, 56 minutes, 7
 * seconds".
 */
function secondsToString($seconds)
{
    $result = '';

    if ($seconds >= 86400) {
        $days = floor($seconds / 86400);
        $seconds = $seconds % 86400;
        $result = $days.' day';
        if ($days != 1) {
            $result .= 's';
        }
        if ($seconds > 0) {
            $result .= ', ';
        }
    }

    if ($seconds >= 3600) {
        $hours = floor($seconds / 3600);
        $seconds = $seconds % 3600;
        $result .= $hours.' hour';
        if ($hours != 1) {
            $result .= 's';
        }
        if ($seconds > 0) {
            $result .= ', ';
        }
    }

    if ($seconds >= 60) {
        $minutes = floor($seconds / 60);
        $seconds = $seconds % 60;
        $result .= $minutes.' minute';
        if ($minutes != 1) {
            $result .= 's';
        }
        if ($seconds > 0) {
            $result .= ', ';
        }
    }

    $result .= $seconds.' second';

    if ($seconds != 1) {
        $result .= 's';
    }

    return $result;
}