如果与该行关联的日期少于 30 天,我正在使用 twig 标记表中的一行。
Twig 的文档指出,要比较两个日期对象,必须先将对象转换为日期,然后再进行比较:
{% if date(yourDate) < date(-'30days') %} ... {% endif %}
但是,它没有指定如何为比较的左侧传递日期格式,我知道 Twig 的日期函数是 PHP 日期的某种包装器。
在 PHP 中我通常会调用:
$myDate = \DateTime::createFromFormat("m/d/Y", $myDate);
但在 Twig 中显然没有办法指定原始日期的格式以便将其转换为另一种格式,或者至少它不在文档中。
这是我试过的:
{% if date(d.LastDate) > date('-30days') %}...{% endif %}
{% if d.LastDate | format("Y-m-d") > date('-30days') %}...{% endif %}
{% if date("m/d/Y", d.LastEmailSentDate) > date('-30days') %}...{% endif %}
这些条件及其变体在 Symfony2 中返回以下异常:
An exception has been thrown during the rendering of a template
("DateTimeZone::__construct(): Unknown or bad timezone (---)")
我的 Controller 以以下格式返回日期:m/d/Y
如果该日期小于 30 天,我只想标记该行。
最佳答案
通过获取自 Unix 纪元以来的秒数来比较两个日期(PHP 日期格式 U
)
{% if d.LastDate|date("U") > "-30 days"|date("U") %}
<p>Less than 30 days old</p>
{% endif %}
关于php - 在 Twig 中如何比较日期是否在 X 天内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19770911/