2012-02-14 54 views
1

私は以下の計算方法がありますか(私はすべての "アクションアイテム"を昨日からプルして "paste_due"に保存しようとしています。CakePHP:日付範囲

public function planner() { 

    $yesterday = date("Y-m-d 23:59:59", strtotime("yesterday")); 
    $conditions = array('ActionItem.due <' => $yesterday, 'ActionItem.agent_id' => '1'); 
    $this->set('past_due', $this->Agent->ActionItem->find('all', array('conditions' => $conditions))); 

    $today = date("Y-m-d 00:00:00", strtotime("today")); 
    $today_end = date("Y-m-d 23:59:59", strtotime("today")); 
    $conditions = array('ActionItem.due >' => $today, 'ActionItem.due <' => $today_end, 'ActionItem.agent_id' => '1'); 
    $this->set('today', $this->Agent->ActionItem->find('all', array('conditions' => $conditions))); 
} 

上記動作しますが、それは最高の場合、私は確かにないよ: - 「今日」)これは私の「エージェント」コントローラ(エージェント「hasManyの」ActionItemとActionItem「belongsToの」エージェント)の内側にあります

答えて

0

いくつかの改善の余地があります(しかし、あなたが言うように、現在のコードがうまくいくはずなので、私の思考の一部です)。すべての

まず、あなただけ、00:00:0023:59:59のように時間に対してチェック完全に回をドロップすると、ちょうどDATETIMEフィールドではなく、DATEフィールドを使用するつもりなら。それはあなたが時間について心配する必要がないので、ずっと簡単にチェックします。 (時間は、アプリケーションの他の部分に不可欠な場合には、以下の例のコードは、それに応じて調整する必要があります。)

さらに私はそれはかなりだ主な理由は、strtotime()とPHPのDateTime機能ではなく、date()を使用したいです私が日時データを扱うときはいつでも私の習慣です。これは、DateTimeがあまりにも多くの手間をかけずに日付と時刻のデータに多くの可能性と柔軟性を追加するためです。このようなものが、おそらく私が行くものです:

public function planner() { 

    // Set the DateTime object (defaults to current date/time) 
    $today = new DateTime(); 

    // Overdue actions (everything older than today) 
    $overdue = $this->Agent->ActionItem->find('all', array(
     'conditions' => array(
      // Check due against a 'Y-m-d' formatted date of today. 
      'ActionItem.due <' => $today->format('Y-m-d'), 
      'ActionItem.agent_id' => '1' 
     ) 
    )); 

    // Actions due today (or in the future) 
    $due = $this->Agent->ActionItem->find('all', array(
     'conditions' => array(
      // Check due against a 'Y-m-d' formatted date of today. 
      'ActionItem.due >=' => $today->format('Y-m-d'), 
      'ActionItem.agent_id' => '1' 
     ) 
    )); 

    // Set the items 
    $this->set(compact('overdue', 'due')); 
}