Rob*_*rto 1 php date symfony twig
我有一个项目,希望以月为单位显示婴儿的当前年龄,也有一个代码以年为单位显示并显示年龄,但是我想以几个月为单位。这是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>
Run Code Online (Sandbox Code Playgroud)
有什么想法吗?
尽管很想在模板/视图中计算值,但最好将逻辑和表示形式分开。
我认为显示婴儿的年龄是将来您可能想要的,所以让我们将其作为方法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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在您的Twig文件中,您可以访问getAge方法:
{{ entity.age }}
Run Code Online (Sandbox Code Playgroud)
因为我很想知道如何做,所以您也可以在Twig中做到这一点;)
{{ date('now').diff((date('2014-1-3'))).format('%y years %m months %d days old') }}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1160 次 |
| 最近记录: |