将秒转换为天,小时,分钟和秒

我想将一个variables$uptime (秒)转换成几天,几小时,几分钟和几秒钟。

例:

 $uptime = 1640467; 

结果应该是:

 18 days 23 hours 41 minutes 

这可以通过DateTime类来实现

使用:

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

function:

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

演示

这是重写包括天的function。 我也改变了variables名,使代码更容易理解…

 /** * 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);

这里是一个简单的8行PHP函数,可以将秒数转换为包含大量秒数的人类可读string:

PHP函数seconds2human()

根据朱利安莫雷诺的答案,但改为给予一个string(而不是一个数组)的响应,只包括所需的时间间隔,而不是假设复数。

这个和最高投票答案的区别是:

259264秒, 这段代码会给

3天,1分钟,4秒

259264秒, 最高的投票答复(由格拉维奇)会给

3天, 0小时 ,1分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); } 

我希望这可以帮助别人。

 gmdate("d H:i:s",1640467); 

结果将是19 23:41:07。 当它比正常的日子多一秒钟时,它将增加一天的值。 这就是为什么它显示19。你可以爆炸你的需要的结果,并解决这个问题。

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

 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 

最简单的方法是创build一个方法,从当前时间$ now的相对时间的DateTime :: diff中以$ seconds的forms返回一个DateInterval,然后您可以将其链接并格式化。 例如:-

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

一个扩展版本的Glavić的优秀的解决scheme ,具有整数validation,解决1秒的问题,以及额外的支持几年和几个月,代价较低的计算机parsing友好,有利于更人性化:

 <?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"

简短,可靠:

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

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

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

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

这是在这里find的代码的稍微修改版本。

 <?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

所有在一个解决scheme。 没有给零的单位。 只会产生你指定的单位数目(默认为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; } 

随意倒票,但一定要在你的代码中尝试。 这可能就是你所需要的。

可以使用我写的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

这是我过去用来减less与你的问题有关的另一个date的function,我的原则是得到多less天,几小时,几分钟和几秒钟,直到一个产品已经过期:

 $expirationDate = strtotime("2015-01-12 20:08:23"); $toDay = strtotime(date('Ymd 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";