I have a Date interval of an entity called worker with a period of time see the next functions:
// Get date of retirement
public function getRetireYear()
{
$this->retireYear = $this->getBirthDay()->add(new \DateInterval('P60Y'));
return $this->retireYear;
}
// Get time left for retirement
public function getTimeToRetirement()
{
// Date of today
$today = new \DateTime('today');
// Calculate date diff between today and retirement day.
$this->timeToRetirement = $today->diff($this->retireYear);
// Return the time to retirement time formated
return $this->formatTimeInterval(
$this->timeToRetirement,
'%r%Y years, %m months, %d days'
);
}
//Format the dateInterval numbers as string
public function formatTimeInterval($aDateDif, $format)
{
return $aDateDif->format($format);
}
The only value that is stored in the database here is $this->getBirthDay()
, then getRetireYear
generates the year of retirement of a worker (birthDay + 60 years).
getTimeToRetirement
gives the time left to retire someone and formatTimeInterval($,$)
is used to format the date Interval.
Now I need to be able to use this dateInterval in different formats, for instance sometimes I just need the year to compare as integer with other values in the views, so I need this year as a single value to be accessible on the views.
I have tried a few things but I do not know the correct way to do it, so I have not get the nicer conclusion to this issue.
Also sometimes I need the month and the day for other tasks, not only the year, this values should be accessible on the views because in the controller I just search for an ArrayColletion of objects and pass it to the view, otherwise I have to go up and dow the array collection.
For more information about the problem you can read this thread