Symfony 如何检查Twig中的今天是否介于两个日期之间?
我想检查今天的日期是否介于数据库中的两个日期之间。这是我的密码Symfony 如何检查Twig中的今天是否介于两个日期之间?,symfony,twig,octobercms,Symfony,Twig,Octobercms,我想检查今天的日期是否介于数据库中的两个日期之间。这是我的密码 {% if today < room.price_start_date and today > room.price_end_date %} <a href="{{'/'|app}}/book/{{room.id}}"><button type="button" class="btn btn-default btn-xs">Book this room</button></a&g
{% if today < room.price_start_date and today > room.price_end_date %}
<a href="{{'/'|app}}/book/{{room.id}}"><button type="button" class="btn btn-default btn-xs">Book this room</button></a>
{% else %}
<a href="{{'/'|app}}/contact"><button type="button" class="btn btn-default btn-xs">Book this room</button></a>
{% endif %}
price\u start\u date
和price\u end\u date
我从数据库中获取它们,它们的列类型是date
你知道如何检查今天是否在房间之间。price\u start\u date
和房间。price\u end\u date
在Twig中吗?试试日期功能:
你可能需要修改一下你的代码,所以我不能给你最好的建议
编辑#2
很抱歉,我没有机会查看关于Twig date函数的文档,但是@Yonel和@Farside这样做了很好@约内尔的观点正是我所关心的,我没有时间给出一个好的答案
如果您使用的是\DateTime
,则这将是您的代码更改:
{% if date() < date(room.price_start_date) and date() > date(room.price_end_date) %}
<a href="{{'/'|app}}/book/{{room.id}}">
<button type="button" class="btn btn-default btn-xs">Book this room</button></a>
{% else %}
<a href="{{'/'|app}}/contact">
<button type="button" class="btn btn-default btn-xs">Book this room</button></a>
{% endif %}
{%if date()date(room.price\u end\u date)%}
{%else%}
{%endif%}
我也改进了格式。我想您只是在检查用户是否可以在该时间范围内单击预订房间。你的代码看起来不错
您可以在开发环境中添加{{dump(room.price\u start\u date)}}
等,以调试实际日期,作为一种故障排除技术。使用\DateTime
实例来比较Twig(以及PHP)中的日期
怎么了
函数返回格式化的日期字符串
因此,您应该将其更改为$today=new\DateTime('today')
并将此实例传递给Twig模板,或在您的条件下直接使用date()
Twig函数
price\u start\u date
和price\u end\u date
我从数据库中获取它们,它们的列类型是date
假设这两个(room.price\u start\u date
和room.price\u end\u date
)是\DateTime
的实例,那么您的细枝代码应该可以正常工作。根据细枝手册,您可以使用该功能。
如果未传递任何参数,函数将返回当前日期
因此,您的代码在TWIG中可能如下所示:
{% if date(room.price_start_date) < date() and date(room.price_end_date) > date() %}
{# condition met #}
{% endif %}
{%if日期(room.price\u开始日期)date()%}
{满足条件}
{%endif%}
对于开放日期的解决方案,考虑扩展@ FARSAND解决方案如下:
{% if ( date(room.price_start_date) is null or date(room.price_start_date) < date()) and
( date(room.price_end_date) is null or date(room.price_end_date) > date()) %}
{# condition met #}
{% endif %}
{%if(date(room.price\u start\u date)为空或date(room.price\u start\u date)date())%}
{满足条件}
{%endif%}
还考虑到,如果不设置开始或结束,它将考虑范围内的所有内容。
实际上,我将比较符号更改为“{如果日期(Hoo.Price),DATE()和日期(Roal.Price OnEnthDead)>DATE()%}并工作。非常感谢@艾哈迈德萨姆,谢谢,你说得对,我用正确的方法更新了比较标志。请随意接受答案,并希望它对其他人也有帮助!只有在同时设置了“开始”和“结束”时,此选项才有效。如果其中任何一个是“打开的”或null都不能正常工作。应该注意的是,yyy-MM-DD
date字符串(date(
)在PHP和twig中可以正确地进行比较
{% if ( date(room.price_start_date) is null or date(room.price_start_date) < date()) and
( date(room.price_end_date) is null or date(room.price_end_date) > date()) %}
{# condition met #}
{% endif %}