树枝日期差异 [英] Twig date difference

查看:17
本文介绍了树枝日期差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于树枝日期差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆