Convert seconds into days, hours, minutes and seconds

后端 未结 24 2283
说谎
说谎 2020-11-22 16:30

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

Example:



        
相关标签:
24条回答
  • 2020-11-22 17:00

    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.

    0 讨论(0)
  • function convert($seconds){
    $string = "";
    
    $days = intval(intval($seconds) / (3600*24));
    $hours = (intval($seconds) / 3600) % 24;
    $minutes = (intval($seconds) / 60) % 60;
    $seconds = (intval($seconds)) % 60;
    
    if($days> 0){
        $string .= "$days days ";
    }
    if($hours > 0){
        $string .= "$hours hours ";
    }
    if($minutes > 0){
        $string .= "$minutes minutes ";
    }
    if ($seconds > 0){
        $string .= "$seconds seconds";
    }
    
    return $string;
    }
    
    echo convert(3744000);
    
    0 讨论(0)
  • 2020-11-22 17:04

    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

    0 讨论(0)
  • 2020-11-22 17:04

    This is a function i used in the past for substracting a date from another one related with your question, my principe was to get how many days, hours minutes and seconds has left until a product has expired :

    $expirationDate = strtotime("2015-01-12 20:08:23");
    $toDay = strtotime(date('Y-m-d H:i:s'));
    $difference = abs($toDay - $expirationDate);
    $days = floor($difference / 86400);
    $hours = floor(($difference - $days * 86400) / 3600);
    $minutes = floor(($difference - $days * 86400 - $hours * 3600) / 60);
    $seconds = floor($difference - $days * 86400 - $hours * 3600 - $minutes * 60);
    
    echo "{$days} days {$hours} hours {$minutes} minutes {$seconds} seconds";
    
    0 讨论(0)
  • 2020-11-22 17:06

    Here it is a simple 8-lines PHP function that converts a number of seconds into a human readable string including number of months for large amounts of seconds:

    PHP function seconds2human()

    function seconds2human($ss) {
    $s = $ss%60;
    $m = floor(($ss%3600)/60);
    $h = floor(($ss%86400)/3600);
    $d = floor(($ss%2592000)/86400);
    $M = floor($ss/2592000);
    
    return "$M months, $d days, $h hours, $m minutes, $s seconds";
    }
    
    0 讨论(0)
  • 2020-11-22 17:07

    There are some very good answers here but none of them covered my needs. I built on Glavic's answer to add some extra features that I needed;

    • Don't print zeros. So "5 minutes" instead of " 0 hours, 5 minutes"
    • Handle plural properly instead of defaulting to the plural form.
    • Limit the output to a set number of units; So "2 months, 2 days" instead of "2 months, 2 days, 1 hour, 45 minutes"

    You can see a running version of the code here.

    function secondsToHumanReadable(int $seconds, int $requiredParts = null)
    {
        $from     = new \DateTime('@0');
        $to       = new \DateTime("@$seconds");
        $interval = $from->diff($to);
        $str      = '';
    
        $parts = [
            'y' => 'year',
            'm' => 'month',
            'd' => 'day',
            'h' => 'hour',
            'i' => 'minute',
            's' => 'second',
        ];
    
        $includedParts = 0;
    
        foreach ($parts as $key => $text) {
            if ($requiredParts && $includedParts >= $requiredParts) {
                break;
            }
    
            $currentPart = $interval->{$key};
    
            if (empty($currentPart)) {
                continue;
            }
    
            if (!empty($str)) {
                $str .= ', ';
            }
    
            $str .= sprintf('%d %s', $currentPart, $text);
    
            if ($currentPart > 1) {
                // handle plural
                $str .= 's';
            }
    
            $includedParts++;
        }
    
        return $str;
    }
    
    0 讨论(0)
提交回复
热议问题