树枝日期差异树枝、差异、日期

2023-09-06 23:39:54 作者:無心

我有一个具有开始日期和结束日期的实体.

I've got an entity with a starting date and an ending date.

是否可以通过使用twig获得它们之间的时间差异?

Is it possible to get the difference in time between them by using twig?

推荐答案

从 PHP 5.3 开始有另外一种选择,无需编写扩展.

Since PHP 5.3 There is another option without to write an extension.

这个例子展示了如何计算复数日/天

This example show how to calc the plural day/days

{# endDate and startDate are strings or DateTime objects #}
{% set difference = date(endDate).diff(date(startDate)) %}
{% set leftDays = difference.days %}
{% if leftDays == 1 %}
  1 day
{% else %}
  {{ leftDays }} days
{% endif %}

解释:

PHP 5.3 DateTime 对象具有 diff() 方法返回一个 DateInterval 对象,结果与 endDatebeginDate树枝

PHP 5.3 DateTime object has diff() method which return a DateInterval object with the result difference between endDate and beginDate Twig

Twig date 函数总是返回一个 DateTime 对象,所以我们可以调用 diff 方法

Twig date function always return a DateTime object so we can call diff method

最后我们可以访问 DateInterval 对象的属性或使用 Twig date 过滤器对其进行格式化.

Finally we can access to the properties of the DateInterval object or format it with the Twig date filter.

注意:如果变量已经是 DateTime 对象.

Note: There is no need of wrap endDate or startDate with the date function if the variable is already a DateTime object.

注意2:DateTime在这里用作DateTimeInterface的同义词.

Note2: DateTime is used here as a synonym of DateTimeInterface.