php - 在 Twig 中如何比较日期是否在 X 天内?

标签 php date symfony twig

如果与该行关联的日期少于 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/

相关文章:

php - 是否可以在我的网络应用程序中使用 Google talk 的音频聊天服务?

javascript - 在 ajax 调用中使用 FormData 发送 JSON 对象和文件,并在 PHP 中访问 json 对象

java - 使用 SimpleDateFormat 将日期转换为友好格式

symfony - 异常处理 app/logs/dev.log

JavaScript 值传递

php - mysql 连接无法正常工作

javascript - 日期列中的 Kendo 网格格式时间问题

c# - 为什么这个日期不在下一年的那一周? (C# 日历)

php - 无法在 Symfony 2 中使用渲染方法找到 Twig 模板

html - 为什么浏览器在 symfony 4 中保留旧代码?