我有一个项目,我想以月为单位显示婴儿的当前年龄,还有一个代码可以计算和显示以年为单位的年龄,但我想要以月为单位。这是 mi 代码。
<td>{% if entity.birthdate %}{{ ('now'|date('Y') - entity.birthdate|date('Y') - 1) + ('now'|date('Y-m-d')|date('U') - entity.birthdate|date('Y-m-d')|date('U') >= 0 ? 1 : 0) }}{% endif %}</td>
有什么想法吗?
最佳答案
虽然在模板/ View 中计算值很诱人,但最好将逻辑和表示分开。
我想显示婴儿的年龄是您将来可能再次需要的东西,所以让我们将其作为 entity
的方法(即 entity 的函数
类)。
// entity.php
class person
{
// Assumption: $birthdate is a DateTime object.
protected $birthdate;
// getAge() outputs something like this: '1 years, 1 months, 8 days old.'
public function getAge()
{
$now = new \DateTime('now');
$age = $this->getBirthdate();
$difference = $now->diff($age);
return $difference->format('%y years, %m months, %d days old.');
}
public function getBirthdate()
{
return $this->birthdate;
}
public function setBirthdate($birthdate)
{
$this->birthdate = $birthdate;
return $this;
}
}
然后在您的 Twig 文件中,您可以访问 getAge
方法:
{{ entity.age }}
因为我很想知道怎么做,你也可以在 Twig 中做到这一点;)
{{ date('now').diff((date('2014-1-3'))).format('%y years %m months %d days old') }}
关于php - 如何使用 twig, symfony2 以月为单位显示当前年龄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41054011/