开发者

php - seconds to time left?

I'm trying to format a date to say how much time is left (in a readable format) from how many seconds are left:

<?php
    $seconds = 23414;
    $date = new DateTime();
    $date->setTime(0, 0, $seconds);
    echo $date->format('z G:i:s');
?>

This example might output something like: 344 11:46:45 which is not what I'd like. It should say something like 6 days,开发者_如何学运维 4:12:36. I just don't see anything here: http://www.php.net/manual/en/function.date.php that would help me format it correctly. Ideas?


I don't know of anything built in, but it's easy enough to write:

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;

}

I haven't tested it thoroughly, but the tests I did run worked fine. You might want to test it yourself a bit before using it.


Something like :

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

Dirty, but should work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜