PHP Symfony2 add 60 years to the both day Datetime

2019-09-09 10:13发布

问题:

I need to add 60 Years to the date of birth of a person/worker, this person is stored in the database and I have the following code to define this person plus the getters and setters:

/**
 * @ORM\Entity
 * @ORM\Table(name="Worker")
 * @ORM\Entity(repositoryClass="Osd\RetireBundle\Entity\WorkerRepository")
 */
class Worker
{
/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $idWorker;

/**
 * @ORM\Column(type="string", length=20)
 */
private $omang;

/**
 * @ORM\Column(type="string", length=100)
 */
private $workerTitle;


/**
 * @ORM\Column(type="string", length=100)
 */
private $workerName;

/**
 * @ORM\Column(type="string", length=100)
 */
private $workerSurname;

/**
 * @ORM\Column(type="date")
 */
private $birthDay;

/**
 * @ORM\Column(type="date")
 */
private $dateOfEmployment;

Inside this person/Worker, I do not really know is is correct to do it there, but I was trying to create a method like this:

    public function getRetireDate (){
   if($this->getBirthDay()) 
       return $retireYear = $this->getBirthDay()->add(new DateInterval('P60Y'));
}

I dont really know where to add the method?, but for now is inside the worker (Im new to symfony). but when ever I call it it gives me this error:

FatalErrorException: Error: Class 'Osd\RetireBundle\Entity\DateInterval' not found in /var/www/Org/src/Osd/RetireBundle/Entity/Worker.php line 202

Any one who has done or knows how and where to achieve this feature? Regards and thank you in advance.

回答1:

I think I have sorted out the problem and your answer @david was really helpful; now my method looks like this:

public function getRetireYear (){
       return $this->retireYear = $this->getBirthDay()->add(new \DateInterval('P60Y'));
}

and I have a private var inside the Worker called $retireYear. that's it. It works wonderfully. Thank you.



回答2:

The getRetireDate() function is in Worker entity. The error that occur is probably you don't have DateInterval entity or you forget to include DateInterval entity to your Worker entity.