【问题标题】:Convert seconds into days, hours, minutes and seconds将秒转换为天、小时、分钟和秒
【发布时间】:2012-01-06 14:40:08
【问题描述】:

我想将变量$uptime(即秒)转换为天、小时、分钟和秒。

例子:

$uptime = 1640467;

结果应该是:

18 days 23 hours 41 minutes

【问题讨论】:

    标签: php date


    【解决方案1】:

    这可以通过DateTime类来实现

    功能:

    function secondsToTime($seconds) {
        $dtF = new \DateTime('@0');
        $dtT = new \DateTime("@$seconds");
        return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
    }
    

    用途:

    echo secondsToTime(1640467);
    # 18 days, 23 hours, 41 minutes and 7 seconds
    

    demo

    【讨论】:

    • 一定要给函数添加验证。 if (empty($seconds)) { return false;}
    • @acoder:我认为这个函数不应该负责验证;验证应该在函数调用之前设置。尽管如此,您的验证仍然是错误的,因为例如它也会通过字母表。
    • @ 作为参数传递给 DateTime 构造函数时是什么意思?
    • @IvankaTodorova:@ 之后的值是 unix 时间戳。
    • $dtF$dtT 在这里代表什么?我认为这个例子可以改进。
    【解决方案2】:

    这是重写为包含天数的函数。我还更改了变量名称以使代码更易于理解...

    /** 
     * Convert number of seconds into hours, minutes and seconds 
     * and return an array containing those values 
     * 
     * @param integer $inputSeconds Number of seconds to parse 
     * @return array 
     */ 
    
    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);
    
        // return the final array
        $obj = array(
            'd' => (int) $days,
            'h' => (int) $hours,
            'm' => (int) $minutes,
            's' => (int) $seconds,
        );
        return $obj;
    }
    

    来源:CodeAid() - http://codeaid.net/php/convert-seconds-to-hours-minutes-and-seconds-(php)

    【讨论】:

    • 最好包含源代码
    • 您能否给这个函数增加天数?
    • @knittledan,看起来不是这样 :)
    • @hsmoore.com 我继续并想出了这个 $days = floor($seconds / (60 * 60 * 24)); // 提取小时数 $divisor_for_hours = $seconds % (60 * 60 * 24); $hours = floor($divisor_for_hours / (60 * 60));
    • 这几天都无法正常工作。您需要从 $hours 中减去 ($days * 24),否则这几天的小时数将在 $days 和 $hours 中重复计算。例如输入 100000 => 1 天 27 小时。这应该是 1 天 3 小时。
    【解决方案3】:

    基于 Julian Moreno 的回答,但改为以字符串(不是数组)的形式给出响应,只包括所需的时间间隔,而不是假设复数。

    此答案与投票最高的答案之间的区别是:

    对于259264 秒,这段代码会给出

    3天1分4秒

    对于259264 秒,投票最高的答案(由 Glavić) 将给出

    3 天,0 小时,1 分钟s 和 4 秒

    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);
    }
    

    我希望这对某人有所帮助。

    【讨论】:

    • 我更喜欢这个,因为它从“1 小时”中删除了“s”,而且,在我的情况下,我想删除天数并且只计算大量小时数,这种方法非常很容易适应
    • 非常好的卢克,保持紧凑和干净!
    【解决方案4】:

    这是一个简单的 8 行 PHP 函数,可将秒数转换为人类可读的字符串,包括大量秒数的月数:

    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";
    }
    

    【讨论】:

    • 简单而高效。虽然我不喜欢“月”这一点。
    • 您应该在答案中包含代码,而不是链接到另一个页面。无法确定您所链接的网站明天是否仍然存在
    • 非常感谢您为我们提供简单的解决方案
    【解决方案5】:
    gmdate("d H:i:s",1640467);
    

    结果将是 19 点 23:41:07。当它比正常一天多一秒时,它正在增加一天的值。这就是它显示 19 的原因。您可以根据需要分解结果并修复此问题。

    【讨论】:

    • 你也可以像这样改进这个代码:$uptime = gmdate("y m d H:i:s", 1640467); $uptimeDetail = explode(" ",$uptime); echo (string)($uptimeDetail[0]-70).' year(s) '.(string)($uptimeDetail[1]-1).' month(s) '.(string)($uptimeDetail[2]-1).' day(s) '.(string)$uptimeDetail[3]; 这也会给你年份和月份的信息。
    • 为了防止 +1 天错误,只需从源时间戳中减去 (24*60*60) 以秒为单位。
    【解决方案6】:

    这里有一些非常好的答案,但没有一个能满足我的需求。我在 Glavic's answer 的基础上添加了一些我需要的额外功能;

    • 不要打印零。所以“5 分钟”而不是“0 小时 5 分钟”
    • 正确处理复数,而不是默认为复数形式。
    • 将输出限制为设定的单位数;所以“2 个月 2 天”而不是“2 个月 2 天 1 小时 45 分钟”

    可以看到代码的运行版本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;
    }
    

    【讨论】:

    • 对我帮助很大
    • 我会根据你在 laravel 中的方式创建函数
    【解决方案7】:

    简短、简单、可靠:

    function secondsToDHMS($seconds) {
        $s = (int)$seconds;
        return sprintf('%d:%02d:%02d:%02d', $s/86400, $s/3600%24, $s/60%60, $s%60);
    }
    

    【讨论】:

    • 在这个答案中进一步解释将有很长的路要走,例如整数常量代表什么以及字符串格式如何与 sprintf 一起工作。
    • 我会做 sprintf('%dd:%02dh:%02dm:%02ds', $s/86400, $s/3600%24, $s/60%60, $s%60 );只是为了更加人性化(例如:0d:00h:05m:00s)。但可能是这里最好的解决方案。
    • 当你有日子的时候,它开始看起来......有趣:14:22:13:18;十四天。
    【解决方案8】:

    Laravel 示例

    Carbon 支持 700 多种语言环境

    \Carbon\CarbonInterval::seconds(1640467)->cascade()->forHumans(); //2 weeks 4 days 23 hours 41 minutes 7 seconds
    

    【讨论】:

      【解决方案9】:

      最简单的方法是创建一个方法,该方法从 DateTime::diff 中返回 DateInterval,该方法与当前时间 $now 之间的相对时间(以 $seconds 为单位)返回,然后您可以将其链接和格式化。例如:-

      public function toDateInterval($seconds) {
          return date_create('@' . (($now = time()) + $seconds))->diff(date_create('@' . $now));
      }
      

      现在将您的方法调用链接到 DateInterval::format

      echo $this->toDateInterval(1640467)->format('%a days %h hours %i minutes'));
      

      结果:

      18 days 23 hours 41 minutes
      

      【讨论】:

        【解决方案10】:

        虽然这是一个很老的问题 - 人们可能会发现这些很有用(不是写得很快):

        function d_h_m_s__string1($seconds)
        {
            $ret = '';
            $divs = array(86400, 3600, 60, 1);
        
            for ($d = 0; $d < 4; $d++)
            {
                $q = (int)($seconds / $divs[$d]);
                $r = $seconds % $divs[$d];
                $ret .= sprintf("%d%s", $q, substr('dhms', $d, 1));
                $seconds = $r;
            }
        
            return $ret;
        }
        
        function d_h_m_s__string2($seconds)
        {
            if ($seconds == 0) return '0s';
        
            $can_print = false; // to skip 0d, 0d0m ....
            $ret = '';
            $divs = array(86400, 3600, 60, 1);
        
            for ($d = 0; $d < 4; $d++)
            {
                $q = (int)($seconds / $divs[$d]);
                $r = $seconds % $divs[$d];
                if ($q != 0) $can_print = true;
                if ($can_print) $ret .= sprintf("%d%s", $q, substr('dhms', $d, 1));
                $seconds = $r;
            }
        
            return $ret;
        }
        
        function d_h_m_s__array($seconds)
        {
            $ret = array();
        
            $divs = array(86400, 3600, 60, 1);
        
            for ($d = 0; $d < 4; $d++)
            {
                $q = $seconds / $divs[$d];
                $r = $seconds % $divs[$d];
                $ret[substr('dhms', $d, 1)] = $q;
        
                $seconds = $r;
            }
        
            return $ret;
        }
        
        echo d_h_m_s__string1(0*86400+21*3600+57*60+13) . "\n";
        echo d_h_m_s__string2(0*86400+21*3600+57*60+13) . "\n";
        
        $ret = d_h_m_s__array(9*86400+21*3600+57*60+13);
        printf("%dd%dh%dm%ds\n", $ret['d'], $ret['h'], $ret['m'], $ret['s']);
        

        结果:

        0d21h57m13s
        21h57m13s
        9d21h57m13s
        

        【讨论】:

          【解决方案11】:
          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);
          }
          

          【讨论】:

          • 你错过了几天
          【解决方案12】:
          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);
          

          【讨论】:

            【解决方案13】:

            我不知道为什么其中一些答案非常冗长或复杂。这是使用DateTime Class 的一个。有点类似于 radzserg 的回答。这将只显示必要的单位,负数将具有“以前”后缀...

            function calctime($seconds = 0) {
            
                $datetime1 = date_create("@0");
                $datetime2 = date_create("@$seconds");
                $interval = date_diff($datetime1, $datetime2);
            
                if ( $interval->y >= 1 ) $thetime[] = pluralize( $interval->y, 'year' );
                if ( $interval->m >= 1 ) $thetime[] = pluralize( $interval->m, 'month' );
                if ( $interval->d >= 1 ) $thetime[] = pluralize( $interval->d, 'day' );
                if ( $interval->h >= 1 ) $thetime[] = pluralize( $interval->h, 'hour' );
                if ( $interval->i >= 1 ) $thetime[] = pluralize( $interval->i, 'minute' );
                if ( $interval->s >= 1 ) $thetime[] = pluralize( $interval->s, 'second' );
            
                return isset($thetime) ? implode(' ', $thetime) . ($interval->invert ? ' ago' : '') : NULL;
            }
            
            function pluralize($count, $text) {
                return $count . ($count == 1 ? " $text" : " ${text}s");
            }
            
            // Examples:
            //    -86400 = 1 day ago
            //     12345 = 3 hours 25 minutes 45 seconds
            // 987654321 = 31 years 3 months 18 days 4 hours 25 minutes 21 seconds
            

            编辑:如果您想压缩上面的示例以使用更少的变量/空间(以牺牲易读性为代价),这里有一个替代版本可以做同样的事情:

            function calctime($seconds = 0) {
                $interval = date_diff(date_create("@0"),date_create("@$seconds"));
            
                foreach (array('y'=>'year','m'=>'month','d'=>'day','h'=>'hour','i'=>'minute','s'=>'second') as $format=>$desc) {
                    if ($interval->$format >= 1) $thetime[] = $interval->$format . ($interval->$format == 1 ? " $desc" : " {$desc}s");
                }
            
                return isset($thetime) ? implode(' ', $thetime) . ($interval->invert ? ' ago' : '') : NULL;
            }
            

            【讨论】:

            • 您可能希望为 calctime 函数添加安全性以防止 0 秒。当前代码抛出错误。在返回中包裹$thetime,例如isset($thetime)
            • 感谢您的建议,您对错误的看法是正确的(我不敢相信我错过了)。我已经相应地更新了代码!
            【解决方案14】:

            Glavić's excellent solution 的扩展版本,具有整数验证,解决 1 s 问题,以及对数年和数月的额外支持,但代价是对计算机解析的友好性降低,而对人类更友好:

            <?php
            function secondsToHumanReadable(/*int*/ $seconds)/*: string*/ {
                //if you dont need php5 support, just remove the is_int check and make the input argument type int.
                if(!\is_int($seconds)){
                    throw new \InvalidArgumentException('Argument 1 passed to secondsToHumanReadable() must be of the type int, '.\gettype($seconds).' given');
                }
                $dtF = new \DateTime ( '@0' );
                $dtT = new \DateTime ( "@$seconds" );
                $ret = '';
                if ($seconds === 0) {
                    // special case
                    return '0 seconds';
                }
                $diff = $dtF->diff ( $dtT );
                foreach ( array (
                        'y' => 'year',
                        'm' => 'month',
                        'd' => 'day',
                        'h' => 'hour',
                        'i' => 'minute',
                        's' => 'second' 
                ) as $time => $timename ) {
                    if ($diff->$time !== 0) {
                        $ret .= $diff->$time . ' ' . $timename;
                        if ($diff->$time !== 1 && $diff->$time !== -1 ) {
                            $ret .= 's';
                        }
                        $ret .= ' ';
                    }
                }
                return substr ( $ret, 0, - 1 );
            }
            

            var_dump(secondsToHumanReadable(1*60*60*2+1)); -> string(16) "2 hours 1 second"

            【讨论】:

              【解决方案15】:

              应排除 0 值并设置正确的单数/复数值的解决方案

              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);
                  }
              }
              

              【讨论】:

                【解决方案16】:
                function secondsToTime($seconds) {
                    $time = [];
                    $minutes = $seconds / 60;
                    $seconds = $seconds % 60;
                    $hours = $minutes / 60;
                    $minutes = $minutes % 60;
                    $days = $hours / 24;
                    $hours = $hours % 24;
                    $month = $days /30;
                    $days = $days % 30;
                    $year = $month / 12;
                    $month = $month % 12;
                    if ((int)($year) != 0){
                        array_push($time,[ "year" => (int)($year)]);
                    }
                    if ($month != 0){
                        array_push($time, ["months" => $month]);
                    }
                    if ($days != 0){
                        array_push($time,["days" => $days]);
                    }
                    if ($hours != 0){
                        array_push($time,["hours" => $hours]);
                    }
                    if ($minutes != 0){
                        array_push($time,["minutes" => $minutes]);
                    }
                    if ($seconds != 0){
                        array_push($time,["seconds" => $seconds]);
                    }
                    return $time;
                }
                

                【讨论】:

                • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
                【解决方案17】:

                一站式解决方案。不给出带零的单位。只会产生您指定的单位数量(默认为 3)。 很长,也许不是很优雅。定义是可选的,但在大型项目中可能会派上用场。

                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;
                }
                

                您可以随意投反对票,但请务必在您的代码中尝试一下。它可能正是您所需要的。

                【讨论】:

                  【解决方案18】:

                  我写的Interval类可以用。也可以反其道而行之。

                  composer require lubos/cakephp-interval
                  
                  $Interval = new \Interval\Interval\Interval();
                  
                  // output 2w 6h
                  echo $Interval->toHuman((2 * 5 * 8 + 6) * 3600);
                  
                  // output 36000
                  echo $Interval->toSeconds('1d 2h');
                  

                  更多信息在这里https://github.com/LubosRemplik/CakePHP-Interval

                  【讨论】:

                    【解决方案19】:

                    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
                    

                    【讨论】:

                      【解决方案20】:

                      这里有一些我喜欢用来获取两个日期之间的持续时间的代码。它接受两个日期,并给你一个很好的句子结构回复。

                      这是对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';
                      }
                      

                      来源:https://gist.github.com/ozh/8169202

                      【讨论】:

                        【解决方案21】:

                        我使用的这个解决方案(回到学习 PHP 的日子)没有任何功能:

                        $days = (int)($uptime/86400); //1day = 86400seconds
                        $rdays = (uptime-($days*86400)); 
                        //seconds remaining after uptime was converted into days
                        $hours = (int)($rdays/3600);//1hour = 3600seconds,converting remaining seconds into hours
                        $rhours = ($rdays-($hours*3600));
                        //seconds remaining after $rdays was converted into hours
                        $minutes = (int)($rhours/60); // 1minute = 60seconds, converting remaining seconds into minutes
                        echo "$days:$hours:$minutes";
                        

                        虽然这是一个老问题,但遇到此问题的新学习者可能会发现此答案很有用。

                        【讨论】:

                          【解决方案22】:
                          a=int(input("Enter your number by seconds "))
                          d=a//(24*3600)   #Days
                          h=a//(60*60)%24  #hours
                          m=a//60%60       #minutes
                          s=a%60           #seconds
                          print("Days ",d,"hours ",h,"minutes ",m,"seconds ",s)
                          

                          【讨论】:

                            【解决方案23】:

                            我正在编辑其中一个代码,以便在出现负值时正常工作。当值为负时,floor() 函数没有给出正确的计数。所以我们需要在floor()函数中使用之前使用abs()函数。 $inputSeconds 变量可以是当前时间戳和所需日期之间的差异。

                            /** 
                             * Convert number of seconds into hours, minutes and seconds 
                             * and return an array containing those values 
                             * 
                             * @param integer $inputSeconds Number of seconds to parse 
                             * @return array 
                             */ 
                            
                            function secondsToTime($inputSeconds) {
                            
                                $secondsInAMinute = 60;
                                $secondsInAnHour  = 60 * $secondsInAMinute;
                                $secondsInADay    = 24 * $secondsInAnHour;
                            
                                // extract days
                                $days = abs($inputSeconds / $secondsInADay);
                                $days = floor($days);
                            
                                // extract hours
                                $hourSeconds = $inputSeconds % $secondsInADay;
                                $hours = abs($hourSeconds / $secondsInAnHour);
                                $hours = floor($hours);
                            
                                // extract minutes
                                $minuteSeconds = $hourSeconds % $secondsInAnHour;
                                $minutes = abs($minuteSeconds / $secondsInAMinute);
                                $minutes = floor($minutes);
                            
                                // extract the remaining seconds
                                $remainingSeconds = $minuteSeconds % $secondsInAMinute;
                                $seconds = abs($remainingSeconds);
                                $seconds = ceil($remainingSeconds);
                            
                                // return the final array
                                $obj = array(
                                    'd' => (int) $days,
                                    'h' => (int) $hours,
                                    'm' => (int) $minutes,
                                    's' => (int) $seconds,
                                );
                                return $obj;
                            }
                            

                            【讨论】:

                              【解决方案24】:

                              @Glavić 答案的一个变体——这个答案隐藏了前导零以获得更短的结果,并在正确的位置使用复数。它还消除了不必要的精度(例如,如果时差超过 2 小时,您可能不在乎多少分钟或秒)。

                              function secondsToTime($seconds)
                              {
                                  $dtF = new \DateTime('@0');
                                  $dtT = new \DateTime("@$seconds");
                                  $dateInterval = $dtF->diff($dtT);
                                  $days_t = 'day';
                                  $hours_t = 'hour';
                                  $minutes_t = 'minute';
                                  $seconds_t = 'second';
                                  if ((int)$dateInterval->d > 1) {
                                      $days_t = 'days';
                                  }
                                  if ((int)$dateInterval->h > 1) {
                                      $hours_t = 'hours';
                                  }
                                  if ((int)$dateInterval->i > 1) {
                                      $minutes_t = 'minutes';
                                  }
                                  if ((int)$dateInterval->s > 1) {
                                      $seconds_t = 'seconds';
                                  }
                              
                              
                                  if ((int)$dateInterval->d > 0) {
                                      if ((int)$dateInterval->d > 1 || (int)$dateInterval->h === 0) {
                                          return $dateInterval->format("%a $days_t");
                                      } else {
                                          return $dateInterval->format("%a $days_t, %h $hours_t");
                                      }
                                  } else if ((int)$dateInterval->h > 0) {
                                      if ((int)$dateInterval->h > 1 || (int)$dateInterval->i === 0) {
                                          return $dateInterval->format("%h $hours_t");
                                      } else {
                                          return $dateInterval->format("%h $hours_t, %i $minutes_t");
                                      }
                                  } else if ((int)$dateInterval->i > 0) {
                                      if ((int)$dateInterval->i > 1 || (int)$dateInterval->s === 0) {
                                          return $dateInterval->format("%i $minutes_t");
                                      } else {
                                          return $dateInterval->format("%i $minutes_t, %s $seconds_t");
                                      }
                                  } else {
                                      return $dateInterval->format("%s $seconds_t");
                                  }
                              
                              }
                              
                              php > echo secondsToTime(60);
                              1 minute
                              php > echo secondsToTime(61);
                              1 minute, 1 second
                              php > echo secondsToTime(120);
                              2 minutes
                              php > echo secondsToTime(121);
                              2 minutes
                              php > echo secondsToTime(2000);
                              33 minutes
                              php > echo secondsToTime(4000);
                              1 hour, 6 minutes
                              php > echo secondsToTime(4001);
                              1 hour, 6 minutes
                              php > echo secondsToTime(40001);
                              11 hours
                              php > echo secondsToTime(400000);
                              4 days
                              

                              【讨论】:

                                【解决方案25】:

                                添加了一些从 Glavić 对 Facebook 风格的帖子计数时间的最佳答案修改而来的格式......

                                        function secondsToTime($seconds) {
                                    $dtF = new \DateTime('@0');
                                    $dtT = new \DateTime("@$seconds");
                                
                                    switch($seconds){
                                        case ($seconds<60*60*24): // if time is less than one day
                                        return $dtF->diff($dtT)->format('%h hours, %i minutes, %s seconds');
                                        break;
                                        case ($seconds<60*60*24*31 && $seconds>60*60*24): // if time is between 1 day and 1 month
                                        return $dtF->diff($dtT)->format('%d days, %h hours');
                                        break;
                                        case ($seconds<60*60*24*365 && $seconds>60*60*24*31): // if time between 1 month and 1 year
                                        return $dtF->diff($dtT)->format('%m months, %d days');
                                        break;
                                        case ($seconds>60*60*24*365): // if time is longer than 1 year
                                        return $dtF->diff($dtT)->format('%y years, %m months');
                                        break;
                                
                                
                                    }
                                

                                【讨论】:

                                  【解决方案26】:

                                  更详细一点,跳过零的时间单位

                                  function secondsToTime($ss) 
                                  {
                                      $htmlOut="";
                                      $s = $ss%60;
                                      $m = floor(($ss%3600)/60);
                                      $h = floor(($ss%86400)/3600);
                                      $d = floor(($ss%2592000)/86400);
                                      $M = floor($ss/2592000);
                                      if ( $M > 0 )
                                      {
                                          $htmlOut.="$M months";      
                                      }
                                      if ( $d > 0 )
                                      {
                                          if ( $M > 0 )
                                           $htmlOut.=", ";
                                          $htmlOut.="$d days";        
                                      }
                                      if ( $h > 0 )
                                      {
                                          if ( $d > 0 )
                                           $htmlOut.=", ";
                                          $htmlOut.="$h hours";       
                                      }
                                      if ( $m > 0 )
                                      {
                                          if ( $h > 0 )
                                           $htmlOut.=", ";            
                                          $htmlOut.="$m minutes";     
                                      }
                                      if ( $s > 0 )
                                      {
                                          if ( $m > 0 )
                                           $htmlOut.=" and ";         
                                          $htmlOut.="$s seconds";     
                                      }       
                                      return $htmlOut;
                                  }   
                                  

                                  【讨论】:

                                    【解决方案27】:

                                    我认为Carbon 会给你所有你想要的变化

                                    所以对于您的示例,您将添加此代码

                                    $seconds = 1640467;
                                    $time = Carbon::now();
                                    $humanTime = $time->diffForHumans($time->copy()->addSeconds($seconds), true, false, 4);
                                    

                                    输出会是这样的

                                    2 周 4 天 23 小时 41 分钟

                                    【讨论】:

                                      【解决方案28】:
                                      foreach ($email as $temp => $value) {
                                          $dat = strtotime($value['subscription_expiration']); //$value come from mysql database
                                      //$email is an array from mysqli_query()
                                          $date = strtotime(date('Y-m-d'));
                                      
                                          $_SESSION['expiry'] = (((($dat - $date)/60)/60)/24)." Days Left";
                                      //you will get the difference from current date in days.
                                      }
                                      

                                      $value 来自数据库。此代码在 Codeigniter 中。 $SESSION 用于存储用户订阅。这是强制性的。我用的就是我的情况,你可以用任何你想要的。

                                      【讨论】:

                                      • 您能否为您的代码添加更多解释? $value 来自哪里?你为什么要介绍一个会话?这如何返回正确的秒、分钟和小时字符串?
                                      • @NicoHaase 回答已更新。
                                      【解决方案29】:

                                      这是我过去使用的一个函数,用于从与您的问题相关的另一个日期中减去一个日期,我的原则是获取产品过期前还剩多少天、小时、分钟和秒:

                                      $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";
                                      

                                      【讨论】:

                                      • 如何也获得周数?示例:5 秒、1 小时、3 天、2 周、1 个月
                                      猜你喜欢
                                      • 1970-01-01
                                      • 2012-09-27
                                      • 1970-01-01
                                      • 1970-01-01
                                      • 2017-05-10
                                      • 2015-06-02
                                      相关资源
                                      最近更新 更多