【问题标题】:User friendly countdown to midnight用户友好的午夜倒计时
【发布时间】:2015-09-15 00:10:01
【问题描述】:

我有一个在午夜运行的 cron 作业,它会重置当天的所有用户限制。我想向我的用户显示Your limits reset in 1 hour 14 minutes 的内容。基本上是倒计时到午夜(服务器时间)。

目前我正在使用它来查找午夜:

strtotime('tomorrow 00:00:00');

它返回一个时间戳,表示午夜结束,但我不知道如何显示用户友好的倒计时。是否有用于此的 PHP 库,或者如果没有库,这很容易吗?

【问题讨论】:

  • 是的,这让我知道距离午夜还剩多少秒,但我不知道如何将其格式化为 1 hour 14 minutes 之类的格式。
  • 一方面,如果你想要一个主动倒计时,你需要使用javascript或客户端的东西。 PHP 可以为您提供(服务器的)初始时间,但客户端代码必须处理计数。签出:SO Q
  • 不需要实时更新,只需要给用户一个粗略的想法。

标签: php time


【解决方案1】:

这只是给你剩下的时间;

$x = time();
$y = strtotime('tomorrow 00:00:00');
$result = floor(($y - $x) / 60);

但是你需要过滤$result;

if ($result < 60) {
    printf("Your limits rest in %d minutes", $result % 60);
} else if ($result >= 60) {
    printf("Your limits rest in %d hours %d minutes", floor($result / 60), $result % 60);
}

【讨论】:

    【解决方案2】:

    由于您正在寻找一个粗略的估计,您可以省略秒数。

    $seconds = strtotime('tomorrow 00:00:00') - now();
    $hours = $seconds % 3600;
    $seconds = $seconds - $hours * 3600;
    $minutes = $seconds % 60;
    $seconds = $seconds - $minutes *60;
    
    echo "Your limit will reset in $hours hours, $minutes minutes, $seconds seconds.";
    

    【讨论】:

      【解决方案3】:

      这很容易,只需要一点数学知识以及找出当时和现在之间的秒数差异。

      // find the difference in seconds between then and now
      $seconds = strtotime('tomorrow 00:00:00') - time(); 
      $hours = floor($seconds / 60 / 60);   // calculate number of hours
      $minutes = floor($seconds / 60) % 60; // and how many minutes is that?
      echo "Your limits rest in $hours hours $minutes minutes";
      

      【讨论】:

      • 我应该在我的原始帖子中提到我已经尝试过这种方法并且它似乎不准确,例如小时计算为1.5427777777778
      • @JamesDawson 我应该记得使用 floor 函数:php.net/manual/en/function.floor.php
      猜你喜欢
      • 2019-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多