Convert seconds into days, hours, minutes and seco

2019-01-01 02:26发布

I would like to convert a variable $uptime which is seconds, into days, hours, minutes and seconds.

Example:

$uptime = 1640467;

Result should be:

18 days 23 hours 41 minutes

标签: php date
18条回答
冷夜・残月
2楼-- · 2019-01-01 02:45
function seconds_to_time($seconds){
     // extract hours
    $hours = floor($seconds / (60 * 60));

    // extract minutes
    $divisor_for_minutes = $seconds % (60 * 60);
    $minutes = floor($divisor_for_minutes / 60);

    // extract the remaining seconds
    $divisor_for_seconds = $divisor_for_minutes % 60;
    $seconds = ceil($divisor_for_seconds);

    //create string HH:MM:SS
    $ret = $hours.":".$minutes.":".$seconds;
    return($ret);
}
查看更多
与风俱净
3楼-- · 2019-01-01 02:45

Short, simple, reliable :

function secondsToDHMS($seconds) {
    $s = (int)$seconds;
    return sprintf('%d:%02d:%02d:%02d', $s/86400, $s/3600%24, $s/60%60, $s%60);
}
查看更多
浅入江南
4楼-- · 2019-01-01 02:45

Here's some code that I like to use for the purpose of getting the duration between two dates. It accepts two dates and gives you a nice sentence structured reply.

This is a slightly modified version of the code found here.

<?php

function dateDiff($time1, $time2, $precision = 6, $offset = false) {

    // If not numeric then convert texts to unix timestamps

    if (!is_int($time1)) {
            $time1 = strtotime($time1);
    }

    if (!is_int($time2)) {
            if (!$offset) {
                    $time2 = strtotime($time2);
            }
            else {
                    $time2 = strtotime($time2) - $offset;
            }
    }

    // If time1 is bigger than time2
    // Then swap time1 and time2

    if ($time1 > $time2) {
            $ttime = $time1;
            $time1 = $time2;
            $time2 = $ttime;
    }

    // Set up intervals and diffs arrays

    $intervals = array(
            'year',
            'month',
            'day',
            'hour',
            'minute',
            'second'
    );
    $diffs = array();

    // Loop thru all intervals

    foreach($intervals as $interval) {

            // Create temp time from time1 and interval

            $ttime = strtotime('+1 ' . $interval, $time1);

            // Set initial values

            $add = 1;
            $looped = 0;

            // Loop until temp time is smaller than time2

            while ($time2 >= $ttime) {

                    // Create new temp time from time1 and interval

                    $add++;
                    $ttime = strtotime("+" . $add . " " . $interval, $time1);
                    $looped++;
            }

            $time1 = strtotime("+" . $looped . " " . $interval, $time1);
            $diffs[$interval] = $looped;
    }

    $count = 0;
    $times = array();

    // Loop thru all diffs

    foreach($diffs as $interval => $value) {

            // Break if we have needed precission

            if ($count >= $precision) {
                    break;
            }

            // Add value and interval
            // if value is bigger than 0

            if ($value > 0) {

                    // Add s if value is not 1

                    if ($value != 1) {
                            $interval.= "s";
                    }

                    // Add value and interval to times array

                    $times[] = $value . " " . $interval;
                    $count++;
            }
    }

    if (!empty($times)) {

            // Return string with times

            return implode(", ", $times);
    }
    else {

            // Return 0 Seconds

    }

    return '0 Seconds';
}

Source: https://gist.github.com/ozh/8169202

查看更多
墨雨无痕
5楼-- · 2019-01-01 02:45

All in one solution. Gives no units with zeroes. Will only produce number of units you specify (3 by default). Quite long, perhaps not very elegant. Defines are optional, but might come in handy in a big project.

define('OneMonth', 2592000);
define('OneWeek', 604800);  
define('OneDay', 86400);
define('OneHour', 3600);    
define('OneMinute', 60);

function SecondsToTime($seconds, $num_units=3) {        
    $time_descr = array(
                "months" => floor($seconds / OneMonth),
                "weeks" => floor(($seconds%OneMonth) / OneWeek),
                "days" => floor(($seconds%OneWeek) / OneDay),
                "hours" => floor(($seconds%OneDay) / OneHour),
                "mins" => floor(($seconds%OneHour) / OneMinute),
                "secs" => floor($seconds%OneMinute),
                );  

    $res = "";
    $counter = 0;

    foreach ($time_descr as $k => $v) {
        if ($v) {
            $res.=$v." ".$k;
            $counter++;
            if($counter>=$num_units)
                break;
            elseif($counter)
                $res.=", ";             
        }
    }   
    return $res;
}

Feel free to down-vote, but be sure to try it in your code. It might just be what you need.

查看更多
梦该遗忘
6楼-- · 2019-01-01 02:47

With DateInterval :

$d1 = new DateTime();
$d2 = new DateTime();
$d2->add(new DateInterval('PT'.$timespan.'S'));

$interval = $d2->diff($d1);
echo $interval->format('%a days, %h hours, %i minutes and %s seconds');

// Or
echo sprintf('%d days, %d hours, %d minutes and %d seconds',
    $interval->days,
    $interval->h,
    $interval->i,
    $interval->s
);

// $interval->y => years
// $interval->m => months
// $interval->d => days
// $interval->h => hours
// $interval->i => minutes
// $interval->s => seconds
// $interval->days => total number of days
查看更多
君临天下
7楼-- · 2019-01-01 02:51

Based on the answer by Julian Moreno, but changed to give the response as a string (not an array), only include the time intervals required and not assume the plural.

The difference between this and the highest voted answer is:

For 259264 seconds, this code would give

3 days, 1 minute, 4 seconds

For 259264 seconds, the highest voted answer (by Glavić) would give

3 days, 0 hours, 1 minutes and 4 seconds

function secondsToTime($inputSeconds) {
    $secondsInAMinute = 60;
    $secondsInAnHour = 60 * $secondsInAMinute;
    $secondsInADay = 24 * $secondsInAnHour;

    // Extract days
    $days = floor($inputSeconds / $secondsInADay);

    // Extract hours
    $hourSeconds = $inputSeconds % $secondsInADay;
    $hours = floor($hourSeconds / $secondsInAnHour);

    // Extract minutes
    $minuteSeconds = $hourSeconds % $secondsInAnHour;
    $minutes = floor($minuteSeconds / $secondsInAMinute);

    // Extract the remaining seconds
    $remainingSeconds = $minuteSeconds % $secondsInAMinute;
    $seconds = ceil($remainingSeconds);

    // Format and return
    $timeParts = [];
    $sections = [
        'day' => (int)$days,
        'hour' => (int)$hours,
        'minute' => (int)$minutes,
        'second' => (int)$seconds,
    ];

    foreach ($sections as $name => $value){
        if ($value > 0){
            $timeParts[] = $value. ' '.$name.($value == 1 ? '' : 's');
        }
    }

    return implode(', ', $timeParts);
}

I hope this helps someone.

查看更多
登录 后发表回答