PHP-还剩几秒钟? [英] php - seconds to time left?

查看:102
本文介绍了PHP-还剩几秒钟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试格式化日期,以说还剩下多少秒(以可读格式)还剩下多少时间:

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

此示例可能会输出类似:344 11:46:45的内容,这不是我想要的.它应该说类似6 days, 4:12:36.我在这里什么都没看到: http://www.php.net/manual/zh-CN/function.date.php 可以帮助我正确设置格式.想法?

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.

这篇关于PHP-还剩几秒钟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆