2012-08-23 72 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