2011-06-06 42 views
1

用下面的代碼,如何在教條中添加2個小時?

protected $token; 
/** @Column(name="assigneddate", type="datetime", columnDefinition="datetime") */ 
private $assigneddate; 


/** @Column(name="expirydate", type="datetime", columnDefinition="datetime") */ 
private $expirydate; 

/** @PreUpdate */ 
public function updated() 
{ 
    //$this->assigneddate = new \DateTime("now"); 
} 
public function __construct() 
{ 

    $this->expirydate = $this->expirydate = new \DateTime("now"); 
    $this->assigneddate = $this->assigneddate = new \DateTime("now"); 

}

如何添加2個小時呢?

+1

請注意,您必須非常小心Doctrine中的DateTime實例。因爲DateTime在PHP中不是不可變的,所以可以使用add()等方法修改該值。但是,除非您創建DateTime的新實例來保存修改後的值,否則Doctrine不會總是將修改後的值返回到數據庫。看到這個頁面進一步討論的主題http://www.doctrine-project.org/docs/orm/2.0/en/cookbook/working-with-datetime.html – 2011-06-11 23:10:26

回答

7

這是更多的PHP問題。要給DateTime PHP對象添加時間,請使用add method,它接受DateInterval對象。在你的情況,如果你要到2小時添加到截止日期:

// Create DateTime object with current time/date 
$this->expirydate = new \DateTime("now"); 
// Add two hours 
$this->expirydate->add(new \DateInterval("PT2H")); 

其中「PT2H」是指「2小時時間週期」,按規定here

+0

我得到一個錯誤:DateInterval :: __ construct() [dateinterval.--construct]:未知格式或錯誤格式(P2H) – 2011-06-07 08:02:51

1

好的。這是PT2H。

$this->expirydate = new \DateTime("now"); 
// Add two hours 
$this->expirydate->add(new \DateInterval("PT2H")); 
+1

對於Doctrine,您需要克隆DateTime對象以便允許Doctrine檢測引用更改並將其保存在數據庫中。 – Maxence 2011-06-21 17:01:27

2

默認學說只允許間隔DAYMONTHYEAR我猜。嘗試添加示例8 HOUR時,會返回錯誤。

但你可以做到這一點竅門:

Let 8 be the number of hours 
Let 24 be the number of hours a day. 

8/24 = decimal presentation of the hour. 

$nHour = 8/24; //result will be: 0.3333333 

然後用它的教義:

DATE_ADD(CURRENT_TIMESTAMP(), $nHour, 'DAY') as dateaddhour 
0

爲了提供幾個其他的替代品,從已經給出答案實體方面。

你並不需要添加或修改日期,你可以創建一個相對格式http://php.net/manual/en/datetime.formats.relative.php

例如一個新的DateTime對象:last friday of june 2011(2011-06-24)

這不是真正清楚OP的行爲或遇到問題後,提供一些方法。

如果想加入2小時創建

/** 
* "now" is implicit 
*/ 
public function __construct() 
{ 
    $this->assigneddate = new \DateTime; 
    $this->expirydate = new \DateTime('+2 hour'); 
} 

或物體時當更新發生

/** 
    * @PreUpdate 
    */ 
    public function updated() 
    { 
     $this->assigneddate = new \DateTime; 
     $this->expirydate = new \DateTime('+2 hour'); 
    } 

另一種替代方法,以確保改性當現有值在原則更新/添加/ sub被調用。使用PHP 5.5您現在可以使用DateTimeImmutable因此,如果您想增加/修改2小時的時間,請使用DateTimeImmutable

public function __construct() 
{ 
    $this->expirydate = new \DateTimeImmutable; 
    $this->assigneddate = new \DateTimeImmutable; 
} 

/** 
* @PreUpdate 
*/ 
public function updated() 
{ 
    $this->assigneddate = new \DateTimeImmutable; 
    $this->expirydate = $this->expirydate->modify('+2 hour'); 
} 

這將導致expirydate〜2小時添加到現有expirydate,因爲DateTimeImmutable總是會返回一個新的對象,其學說也就那麼過程。 http://php.net/manual/en/class.datetimeimmutable.php