2013-11-15 38 views
0

CakePHP的問題中的DateTime對象傳遞給做差異計算

我想從一個形式 - shift_start的日期時間字段,以拉動和比較它的價值shift_end這也是一個日期時間,並計算以小時爲單位的差異。這一切都在我的控制器中。我曾嘗試使用構造函數$start = new DateTime($this->shift_start)來存儲shift_start的值及其不同變化,其中包括用$start = $this->shift_start之後的手動設置,但無濟於事。

我們想打電話給$difference = $start->diff($end),但是當我們運行它時,我們會得到空白值或零。

任何洞察將有所幫助。

更新:改變它,所以shift_start和shift_end只是正確格式的字符串。

 $start = strtotime($this->shift_start); 
     $end = strtotime($this->shift_end); 
     $datetime1 = new DateTime($start); 
     $datetime2 = new DateTime($end); 
     $difference = $datetime1->diff($datetime2); 
+0

向我們展示你試圖 –

+0

你也可以使用日期時間差異規避代碼的時代轉換爲使用時間戳的strtotime(),減去時間戳,然後通過60 * 60除以將它轉換成小時。 – Kai

+0

這是我嘗試過的一種變體..我稍微改變了一下代碼,以便在幾小時內獲取的字段只是正確格式的字符串,而不是無濟於事。我仍想傳入'H:i:s'並計算兩個對象之間的差異,但由於某些原因無法正確創建新的DateTime對象。 –

回答

1

也許你不使用的strtotime正確

$start = date('Y-m-d', strtotime($this->shift_start)); 
$end = date('Y-m-d', strtotime($this->shift_end)); 
$datetime1 = new DateTime($start); 
$datetime2 = new DateTime($end); 
$difference = $datetime1->diff($datetime2); 

編輯

既然你使用G工作:I:S,那麼你需要做

$shift_start = "05:05:05"; 
$shift_end = "10:10:10"; 
$start = date('G:i:s', strtotime($shift_start)); 
$end = date('G:i:s', strtotime($shift_end)); 
$datetime1 = new DateTime($start); 
$datetime2 = new DateTime($end); 
$difference = $datetime1->diff($datetime2); 
var_dump($difference->format('%h')); //prints string(1) "5" 
+0

這似乎不起作用 –

+0

你可以粘貼你得到的輸出嗎?另外,shift_start和shift_end –

+0

的內容實際上沒有發生任何事情......我沒有得到一個錯誤,但我期待在'hours_worked'中有0以外的值。我用這個代碼$ start = date('H:i:s',strtotime($ this-> shift_start)); \t \t \t $ end = date('H:i:s',strtotime($ this-> shift_end)); \t \t \t $ datetime1 = new DateTime($ start); \t \t \t $ datetime2 = new DateTime($ end); \t \t \t $ difference = $ datetime1-> diff($ datetime2); \t \t \t $ this-> Shift-> set('hours_worked',$ difference-> h); –

0

日期時間字段不必轉換才能使用它使用PHP的DateTime函數。您可以直接將Y-m-d H:i:s格式的字符串傳遞給它。例如,通過使用模型中的field方法:

# app/Model/Shift.php 
public function duration($id) { 
    $start = new DateTime($this->field('shift_start', array('id' => $id)); 
    $end = new DateTime($this->field('shift_end', array('id' => $id)); 
    return $start->diff($end); 
} 

這將返回一個DateInterval對象具有一定的轉變(由$id識別)的開始和結束時間之間的所有差異信息。然後,您可以從您的ShiftsController訪問這些數據是這樣的:

# app/Controller/ShiftsController.php 
public function view($id) { 
    // Check if the shift exists 
    if (!$this->Shift->exists($id)) { 
     throw new NotFoundException(__('Unknown shift #' . $id)); 
    } 

    // Get it's data 
    $shift = $this->Shift->findById($id); 

    // And the duration 
    $duration = $this->Shift->duration($shift['Shift']['id']); 
} 
+0

當我嘗試這個,我得到「調用未定義的方法字段」 –

+0

@johnsmith然後,你沒有把這種方法放在你的Shift模型,但更可能在你的控制器。編輯答案的評論,顯示什麼去哪裏。 – Oldskool