Convert seconds into days, hours, minutes and seconds

后端 未结 24 2318
说谎
说谎 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 16:53

    Solution that should exclude 0 values and set correct singular/plural values

    use DateInterval;
    use DateTime;
    
    class TimeIntervalFormatter
    {
    
        public static function fromSeconds($seconds)
        {
            $seconds = (int)$seconds;
            $dateTime = new DateTime();
            $dateTime->sub(new DateInterval("PT{$seconds}S"));
            $interval = (new DateTime())->diff($dateTime);
            $pieces = explode(' ', $interval->format('%y %m %d %h %i %s'));
            $intervals = ['year', 'month', 'day', 'hour', 'minute', 'second'];
            $result = [];
            foreach ($pieces as $i => $value) {
                if (!$value) {
                    continue;
                }
                $periodName = $intervals[$i];
                if ($value > 1) {
                    $periodName .= 's';
                }
                $result[] = "{$value} {$periodName}";
            }
            return implode(', ', $result);
        }
    }
    

提交回复
热议问题