php 将秒转换为天、小时、分钟和秒
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8273804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert seconds into days, hours, minutes and seconds
提问by Florian
I would like to convert a variable $uptime
which is seconds, into days, hours, minutes and seconds.
我想将$uptime
秒的变量转换为天、小时、分钟和秒。
Example:
例子:
$uptime = 1640467;
Result should be:
结果应该是:
18 days 23 hours 41 minutes
回答by Glavi?
This can be achieved with DateTime
class
这可以通过DateTime
类来实现
Use:
用:
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');
}
回答by Julian Moreno
This is the function rewritten to include days. I also changed the variable names to make the code easier to understand...
这是重写的函数以包含天数。我还更改了变量名称以使代码更易于理解...
/**
* 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;
}
Source: CodeAid() - http://codeaid.net/php/convert-seconds-to-hours-minutes-and-seconds-(php)
来源:CodeAid() - http://codeaid.net/php/convert-seconds-to-hours-minutes-and-seconds-(php)
回答by Luke Cousins
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.
基于 Julian Moreno 的回答,但更改为将响应作为字符串(而不是数组)提供,仅包含所需的时间间隔,而不假设为复数。
The difference between this and the highest voted answer is:
这个和得票最高的答案之间的区别是:
For 259264
seconds, this codewould give
几259264
秒钟后,此代码将给出
3 days, 1 minute, 4 seconds
3天1分4秒
For 259264
seconds, the highest voted answer (by Glavi?)would give
几259264
秒钟内,最高投票的答案(由 Glavi?)将给出
3 days, 0 hours, 1 minutes and4 seconds
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);
}
I hope this helps someone.
我希望这可以帮助别人。
回答by snippetsofcode
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:
这是一个简单的 8 行 PHP 函数,它将秒数转换为人类可读的字符串,其中包括大量秒的月数:
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";
}
回答by Caner SAYGIN
gmdate("d H:i:s",1640467);
Result will be 19 23:41:07. When it is just one second more than normal day, it is increasing the day value for 1 day. This is why it show 19. You can explode the result for your needs and fix this.
结果将是 19 23:41:07。当它仅比正常天多一秒时,它会增加 1 天的天值。这就是它显示 19 的原因。您可以根据需要分解结果并修复此问题。
回答by Ramy Nasr
There are some very good answers here but none of them covered my needs. I built on Glavic's answerto add some extra features that I needed;
这里有一些非常好的答案,但没有一个能满足我的需求。我在Glavic 的回答基础上添加了一些我需要的额外功能;
- 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"
- 不要打印零。所以“5分钟”而不是“0小时5分钟”
- 正确处理复数而不是默认为复数形式。
- 将输出限制为一定数量的单位;所以“2个月,2天”而不是“2个月,2天,1小时,45分钟”
You can see a running version of the code here.
您可以看到代码的运行版本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;
}
回答by Jérémie Germain
Short, simple, reliable :
简短、简单、可靠:
function secondsToDHMS($seconds) {
$s = (int)$seconds;
return sprintf('%d:%02d:%02d:%02d', $s/86400, $s/3600%24, $s/60%60, $s%60);
}
回答by Trent Renshaw
The simplest approach would be to create a method that returns a DateInterval from the DateTime::diff of the relative time in $seconds from the current time $now which you can then chain and format. For example:-
最简单的方法是创建一个方法,该方法从当前时间 $now 的 $seconds 中的相对时间的 DateTime::diff 返回 DateInterval,然后您可以链接和格式化。例如:-
public function toDateInterval($seconds) {
return date_create('@' . (($now = time()) + $seconds))->diff(date_create('@' . $now));
}
Now chain your method call to DateInterval::format
现在将您的方法调用链接到 DateInterval::format
echo $this->toDateInterval(1640467)->format('%a days %h hours %i minutes'));
Result:
结果:
18 days 23 hours 41 minutes
回答by Madushanka Sampath
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);
回答by James Doherty
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);
}