在Twig中比较日期和特定日期,并将DateTime转换为字符串

22
  1. How can I compare two dates in Twig when the first one comes from the dababase and the second is clear - 2012-12-31? I tried with

    {% if  dom.dueDate|date('Y-m-d') > 2012-12-31 %}
    

    but I don't get the result I want. :(

  2. I have a DateTime field but I couldn't find a filter for DateTime in Twig and when I use |date('Y-m-d') it prints only the date without the hour :(

如果有人能帮我解决问题,我会非常高兴和感激!

3个回答

37
尝试使用时间戳进行比较:
{% if dom.dueDate|date('U') > '2012-12-31'|date('U') %}

而这段代码是用来添加小时、分钟和秒数的

{{ dom.dueDate|date('Y-m-d H:i:s') }}

哦,非常感谢!你无法想象我有多感激。我搜索了两个但是什么都没找到。现在一切都正常工作了!再次非常感谢! - Faery
1
新年快乐版 {% if 'now'|date('U') > '2013-12-20'|date('U') and 'now'|date('U') < '2014-01-09'|date('U') %} :-) - Alexey B.
1
在使用“U”参数时,请考虑您所处的时区。因为它是指UTC时间戳。您所在的城市可能位于不同的UTC时区,如UTC+2或UTC-1等。 - Ali Emre Çakmakoğlu
谢谢@AlexeyB。'now'函数很方便! - Edmunds22
太棒了,非常感谢!真的帮了我很大的忙。 - bhu Boue vidya

12
从twig 1.6+开始,根据官方文档的说法,比较日期的正确方法是使用date函数:
{% if dom.dueDate > date('2012-12-31') %}

@RaymondA 我不确定那个,因为原帖实际上是比较 DateTime 和 DateTime,而不是 Date 和 Date,因此被接受的答案包含了正确的方法。 - thex
@thex 我保留了答案中使用的数据,但实际上代码是使用 DateTime 对象的。日期 "twig" 方法只是 PHP 方法的包装器,所以如果需要,只需添加小时即可。 - giosh94mhz
@giosh94mhz 你是对的,你的表达式得出了1.)中要求的正确结果...忘记我的帖子吧。但那也不是我想说的,我完全说错了。我的意思是被接受的答案考虑了DateTime格式,这是在2.)中所要求的,而你的只涵盖了1.) - 比较。但没关系,两个答案都包含有用的信息。 - thex

0
{% if date(dom.dueDate) > date(2012-12-31) %}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接