我正在尝试格式化一个日期,以说明剩下多少秒还剩多少时间(以可读格式):
<?php
$seconds = 23414;
$date = new DateTime();
$date->setTime(0, 0, $seconds);
echo $date->format('z G:i:s');
?>
此示例可能会输出类似于:344 11:46:45
的内容,而这不是我想要的内容。应该说6 days, 4:12:36
之类的东西。我在这里看不到任何内容:http://www.php.net/manual/en/function.date.php可以帮助我正确格式化。想法?
答案 0 :(得分:2)
我不知道内置任何内容,但写起来很容易:
function formatSeconds($secondsLeft) {
$minuteInSeconds = 60;
$hourInSeconds = $minuteInSeconds * 60;
$dayInSeconds = $hourInSeconds * 24;
$days = floor($secondsLeft / $dayInSeconds);
$secondsLeft = $secondsLeft % $dayInSeconds;
$hours = floor($secondsLeft / $hourInSeconds);
$secondsLeft = $secondsLeft % $hourInSeconds;
$minutes= floor($secondsLeft / $minuteInSeconds);
$seconds = $secondsLeft % $minuteInSeconds;
$timeComponents = array();
if ($days > 0) {
$timeComponents[] = $days . " day" . ($days > 1 ? "s" : "");
}
if ($hours > 0) {
$timeComponents[] = $hours . " hour" . ($hours > 1 ? "s" : "");
}
if ($minutes > 0) {
$timeComponents[] = $minutes . " minute" . ($minutes > 1 ? "s" : "");
}
if ($seconds > 0) {
$timeComponents[] = $seconds . " second" . ($seconds > 1 ? "s" : "");
}
if (count($timeComponents) > 0) {
$formattedTimeRemaining = implode(", ", $timeComponents);
$formattedTimeRemaining = trim($formattedTimeRemaining);
} else {
$formattedTimeRemaining = "No time remaining.";
}
return $formattedTimeRemaining;
}
我没有彻底测试过,但是我运行的测试运行良好。在使用它之前,您可能想要自己测试一下。
答案 1 :(得分:0)
类似的东西:
$SECONDS_IN_MINUTE = 60;
$SECONDS_IN_HOUR = $SECONDS_IN_MINUTE * 60;
$SECONDS_IN_DAY = $SECONDS_IN_HOUR * 24;
$days = 0;
$hours = 0;
$minutes = 0;
$seconds = 23414;
while ($seconds > $SECONDS_IN_DAY) {
$days++;
$seconds -= $SECONDS_IN_DAY;
}
while ($seconds > $SECONDS_IN_HOUR) {
$hours++;
$seconds -= $SECONDS_IN_HOUR;
}
while ($seconds > $SECONDS_IN_MINUTE) {
$minutes++;
$seconds -= $SECONDS_IN_MINUTE;
}
echo ($days > 0 ? $days . ' day' . ($days > 1 ? 's' : '') . ', ' : '') .
$hours . ':' . str_pad($minutes, 2, '0', STR_PAD_LEFT) . ':' . str_pad($seconds, 2, '0', STR_PAD_LEFT);
很脏,但应该有用。