2012-02-13 56 views
1

我在數據庫如何做到這一點倒計時

我得到的當前日期的最後一天,讓我們假設是UTC

class Datecalc 
{ 

    public $year; 
    public $month; 
    public $day; 
    public $hour; 
    public $min; 
    public $sec; 

    function diff($start,$end = false) 
    { 
     if($start > $end) 
     { 
      $this->day = 0; 
      $this->hour = "00"; 
      $this->min = "00"; 
      $this->sec = "00"; 
      return false; 

     } 
     if(!$end) { $end = time(); } 
     if(!is_numeric($start) || !is_numeric($end)) { return false; } 
     $start = date('Y-m-d H:i:s',$start); 
     $end = date('Y-m-d H:i:s',$end); 
     $d_start = new DateTime($start); 
     $d_end  = new DateTime($end); 
     $diff = $d_start->diff($d_end); 

     $this->year = $diff->format('%y'); 
     $this->month = $diff->format('%m'); 
     $this->day  = $diff->format('%d'); 
     $this->hour  = $diff->format('%H'); 
     $this->min  = $diff->format('%I'); 
     $this->sec  = $diff->format('%S'); 

     return true; 
    } 

} 

我用這個功能來計算時間差,但問題是我不能把天數計爲99,而當日期是00:00:00,天-1,它的設置爲98和時間23:59:59,在這個代碼中它的一切都很好,但是如果天數高於30,重置爲01,我想你明白我想說什麼,請幫助!

換句話說

我需要單獨算日子,並需要綁定到天

+0

它總是一個好主意,做日期計算與時間戳,因爲你只有一個數字來處理,並可以轉換時間戳後計算適當的天/月/任何字符串。 – Corubba 2012-02-13 15:09:47

+0

將您的日期轉換爲EPOC標準,做差異,然後手動將其轉換爲月/日等。 – Mikhail 2012-02-13 15:13:18

+0

哦,男士,我真的很困惑,你能給我一個幫助我理解的小例子嗎? – 2012-02-13 15:14:58

回答

1

您使用的方法永遠不會讓你得到天數> 30,因爲高於30的任何天將被轉換的時間其他月份...

這可能是你最好的辦法:
http://www.prettyscripts.com/code/php/php-date-difference-in-days
或者
http://www.bizinfosys.com/php/date-difference.html
(簡單的谷歌搜索BTW ...)

+0

我已經搜索了很長時間,我已經創建了一個計算日期的腳本,但我該如何將時間綁定到那些日子,因爲當時間變爲00:00:00時,日子仍然如此 – 2012-02-13 15:23:54

+0

函數dateDiff($ d1,$ d2){ //返回兩個日期之間的天數: return round(abs(strtotime($ d1)-strtotime($ d2))/ 86400); } //結束函數dateDiff好吧我有這個腳本,但我怎麼能綁定實時???,當時間設置爲00:00:00將天倒數? – 2012-02-13 15:24:38

+0

非常感謝你! – 2012-02-13 15:50:35

1

首先,在檢查$ start是否大於$ end之前,您應該檢查$ end是否爲false。

也就是說,diff方法返回一個DateInterval對象(http://us.php.net/manual/en/class.dateinterval.php),它具有多個選項,包括日期以及年,月,日等。您可能想要使用已經由diff方法返回的內容,而不是格式化函數。

$diff = $d_start->diff($d_end); 
echo 'Total days difference: '.$diff->days; 
echo 'Year, Month, Days, time difference: '. 
$diff->y.' y, '.$diff->m.' m, '.$diff->d.' d, '.$diff->h.' h, '.$diff->i.' m, '.$diff->s.' s, '; 
+0

非常感謝你的這篇文章,真的很有幫助 – 2012-02-13 16:16:53