PHP date_create() 上的 Twig 异常
Twig exception on PHP date_create()
我想根据她的生日计算一个选民的年龄,在我的实体中,我创建了一个这样的函数
//voters.php
public function getAge()
{
$birthday = $this->birthday;
$age = date_diff(date_create($birthday),date_create('today'))->y;
return $age;
}
我在 Twig 中渲染是这样的
<td>{{ entity.getAge() }}</td>
但是显示如下错误:
"An exception has been thrown during the rendering of a template ("Warning: date_create() expects parameter 1 to be string, object given") in DuBundle:Voters:index.html.twig at line 32."..
如何解决这个问题?我在带有 Php 模板的 Symfony 1.4 中的旧项目中使用它,它呈现选民的当前年龄而没有 problem.Why 它在 Twig 上不起作用?
在旧的 Symfony 1.4 中我使用这种方式
<td><?php echo date_diff(date_create($total->birthday), date_create('today'))->y; ?></td>
如果您的 $birthday
字段是 DateTime
对象,您可以使用这种方法:
public function getAge()
{
if (!$this->birthday) return "";// put here what you want if no birthdayprovided
$now = new \DateTime('now');
return $now->diff($this->birthday)->format("%y");
}
希望对您有所帮助
我想根据她的生日计算一个选民的年龄,在我的实体中,我创建了一个这样的函数
//voters.php
public function getAge()
{
$birthday = $this->birthday;
$age = date_diff(date_create($birthday),date_create('today'))->y;
return $age;
}
我在 Twig 中渲染是这样的
<td>{{ entity.getAge() }}</td>
但是显示如下错误:
"An exception has been thrown during the rendering of a template ("Warning: date_create() expects parameter 1 to be string, object given") in DuBundle:Voters:index.html.twig at line 32."..
如何解决这个问题?我在带有 Php 模板的 Symfony 1.4 中的旧项目中使用它,它呈现选民的当前年龄而没有 problem.Why 它在 Twig 上不起作用?
在旧的 Symfony 1.4 中我使用这种方式
<td><?php echo date_diff(date_create($total->birthday), date_create('today'))->y; ?></td>
如果您的 $birthday
字段是 DateTime
对象,您可以使用这种方法:
public function getAge()
{
if (!$this->birthday) return "";// put here what you want if no birthdayprovided
$now = new \DateTime('now');
return $now->diff($this->birthday)->format("%y");
}
希望对您有所帮助