With the following code,
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");
}
How do I add 2 hours to this?
This is more of a PHP question. To add time to a DateTime PHP object, you use the add method, which accepts a DateInterval object. In your case, if you want to add 2 hours to the expiry date:
Where "PT2H" means a "period time of 2 hours", as specified here.
Ok. It's PT2H.
By default doctrine only allowing intervals
DAY
,MONTH
andYEAR
I guess. When trying to date add example 8 HOUR, it returns an error.But you can do this trick:
then use it in doctrine as:
To provide a couple of other alternatives to the already given answers from the entity side.
You don't need to add or modify the date, you can create a new DateTime object with Relative Formats http://php.net/manual/en/datetime.formats.relative.php
For example:
last friday of june 2011
(2011-06-24)It wasn't really clear on the behavior the OP was after or having issues with, so providing a few methods.
If wanting to add 2 hours when the object is created
Or when an update occurs
Another alternative to ensure the existing value is updated in Doctrine when modified/add/sub is called on it. With
PHP 5.5
you can now useDateTimeImmutable
So if you are wanting to increment/modify theexpirydate
time by 2 hours.This will cause the
expirydate
to add 2 hours to the existing expirydate, sinceDateTimeImmutable
will always return a new object, which doctrine will then process. http://php.net/manual/en/class.datetimeimmutable.php