2012-08-23 30 views
3

场景:记录已输入数据库。如何用PHP获得午夜时间的小时数

我试图找出下列公式:

  1. 如何获得的小时数,因为加入的记录。
  2. 如何获得自添加记录 以来一直保留到午夜的时间。

鉴于这些时间:

  • 日期/时间:2012-08-22 20时11分二十秒
  • 时间戳:1345684280
  • 今晚午夜:2012年8月23日00:00:00
  • 午夜时间戳:1345698000

我觉得就像我在正确的轨道上。只需要一些适当的数学来做计算?我在数学上很可怕。任何帮助或指导,将不胜感激。我不想找人为我完成这个任务。只是寻找我做错的建议,或者我可以做得更好。也许可以解释实现我的目标所需的数学公式。

这是我到目前为止有:

class tools{ 

    public function __construct(){ 
    } 

    public function check_time($time, $request){ 
     $time = strtotime($time); 
     if($request == 'since'){ 
      $theTime = time() - $time; 
      $prefix = 'Since:'; 
     } elseif($request == 'until'){ 
      $midnight = mktime(0, 0, 0, date('n'), date('j'), date('Y')); 
      $theTime = $midnight - $time; 
      $prefix = 'Until:'; 
     } 

     $tokens = array (
      31536000 => 'year', 
      2592000 => 'month', 
      604800 => 'week', 
      86400 => 'day', 
      3600 => 'hour', 
      60 => 'minute', 
      1 => 'second' 
     ); 

     foreach($tokens as $unit => $text){ 
      if($theTime < $unit) continue; 
      $duration = floor($theTime/$unit); 
      return $prefix.' '.$duration.' '.$text.(($duration>1)?'s':''); 
     } 
    } 
}// EoF tools class 

$tools = new tools(); 

print_r($tools->check_time('2012-08-22 20:11:20', 'since')); 
print_r($tools->check_time('2012-08-22 20:11:20', 'until')); 

回答

10

这里的解决方案非常简单。有一个小错误导致你所有的问题。

在你的代码中,你有这个计算午夜。

$midnight = mktime(0, 0, 0, date('n'), date('j'), date('Y')); 

这是不正确的简单的事实,它是用今天的午夜(这本来今天00:00,然而,许多小时前从现在开始,你想明天午夜,因为它被认为是00:0024小时。时间就是明天去做正确的方法是一样的:

$midnight = strtotime("tomorrow 00:00:00"); 

只需记住的strtotime()立足事事休GMT的,所以一定要在文件/应用程序设置默认的时区。

我希望我的回答很清楚,并解释了您发布的代码错误的原因以及如何解决问题。

+3

或简单strtotime('明天')每http://www.php.net/manual/en/datetime.formats.relative.php –

+0

感谢您的解释。这对我非常有用 – xzdead

-1

你可以试试这个:

$now = strtotime('2012-08-22 20:11:20'); 
$midnight = strtotime('2012-08-23 00:00:00'); 
$difference = $midnight - $now; 

echo date("H:i:s", $difference); 
3

也许这样的事情?我不得不承认没有完全了解你的期望的输出是什么:

$d1 = new DateTime('2012-08-22 20:11:20');                       
$d2 = new DateTime('2012-08-23 00:00:00'); 

$interval = $d1->diff($d2); 

echo $interval->format('%h hours %i minutes and %s seconds'); 
+0

我已更新我的问题以获得更多清晰度和代码修订。 –

0

午夜时未指定时间做最好的方式,它必须比第二天不多:

<?php 
$datetime1 = new DateTime(date('Y-m-d H:i:s'));//current datetime object 
$datetime2 = new DateTime(date('Y-m-').date(d));//next day at midnight 
$interval = $datetime1->diff($datetime2);//diference 
echo $interval->format('H');printing only hours (same as date format) 
?> 

,如果你想知道更多:php date_diff

+0

这不会给我第二天午夜,但当天午夜(日期时间2),是功能好吗? – Radek