我尝试使用以下代码在 Twig 中显示 DateInterval:
{{ event.endTime.diff(event.startTime)|date("i's''") }}
其中event
是一个获取2个DateTime对象的实体:endTime
和startTime
。使用该命令我得到以下输出:
i's''
而不是像08'15''
那样的min'sec''
date doc中说那个
The date filter accepts [...] DateInterval instances
此工作用于显示日期对象的分钟和秒。
请注意,这样做: {{ (event.endTime.diff(event.startTime))|date("i's''") }}
不会改变任何内容
我也尝试过 {{ date(event.endTime.diff(event.startTime))|date("i's''") }}
但这会导致异常 Object of DateInterval 类无法转换为字符串
我还看到了 Twig Extensions 中的 time_diff
但这返回一个字符串(in
或 ago
)而不是 Date 对象,然后我无法按我想要的方式显示它。
如果您需要更多信息,请告诉我。感谢您的帮助。
最佳答案
正如@Yoshi 所说:
(new \DateTime('tomorrow'))->diff(new \DateTime('now'))->format("i's''")
also gives"i's''"
, so I'd say this is not a twig-thing. From the manual:"The following characters are recognized in the format parameter string. Each format character must be prefixed by a percent sign (%)."
因此,为了解决我的问题,我必须这样做:
{{ event.endTime.diff(event.startTime)|date("%i'%s''") }}
关于date - 在 Twig 中显示日期间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41760435/