Convert seconds into days, hours, minutes and seconds

后端 未结 24 2286
说谎
说谎 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: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.

     $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

提交回复
热议问题