【问题标题】:Displaying a DateInterval in Twig在 Twig 中显示 DateInterval
【发布时间】:2017-06-05 06:03:46
【问题描述】:

我正在尝试使用以下代码在 Twig 中显示 DateInterval:

{{ event.endTime.diff(event.startTime)|date("i's''") }}

其中event 是一个获得2 个DateTime 对象的实体:endTimestartTime。使用该命令,我得到了以下输出:

i's''

而不是min'sec''08'15''

date doc里说

日期过滤器接受 [...] DateInterval 实例

这项工作用于显示日期对象的分钟和秒。

请注意,这样做:{{ (event.endTime.diff(event.startTime))|date("i's''") }} 不会改变任何东西

我也试过{{ date(event.endTime.diff(event.startTime))|date("i's''") }},但这会导致异常Object of class DateInterval could not be converted to string

我还从Twig Extensions 看到了time_diff,但这会返回一个字符串(inago)而不是 Date 对象,然后我无法按我的意愿显示它。

如果您需要更多信息,请告诉我。感谢您的帮助。

【问题讨论】:

  • (new \DateTime('tomorrow'))->diff(new \DateTime('now'))->format("i's''") 也给出了"i's''",所以我想说这不是twig-thing。来自the manual“在格式参数字符串中可以识别以下字符。每个格式字符必须以百分号 (%) 为前缀。”
  • 非常感谢,事实上我必须在is之前加上%

标签: date twig symfony dateinterval


【解决方案1】:

format方法中的参数'i''s'小写时,显示的值较小时超过 10,请输入一位数。

例如,如果您需要通过显示前导零 (05:02) 来显示 5 分 2 秒的时间。您必须将参数大写,它会是这样的:

{{ event.endTime.diff(event.startTime)|date("%I:%S") }}

允许的参数见:DateInterval format

【讨论】:

    【解决方案2】:

    正如@Yoshi 所说:

    (new \DateTime('tomorrow'))->diff(new \DateTime('now'))->format("i's''") 也提供"i's''",所以我会说这不是树枝。来自手册:

    "格式参数中识别出以下字符 细绳。每个格式字符必须以百分号 (%) 为前缀。"

    所以要解决我的问题,我只需要这样做:

    {{ event.endTime.diff(event.startTime)|date("%i'%s''") }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      • 1970-01-01
      • 2016-05-10
      • 2021-07-07
      • 2017-07-02
      • 2019-09-30
      相关资源
      最近更新 更多