10

I want to compare two dates. I want to make a condition which checks if the date in my database is older than the date in two days.

Here are my two variables:

{<f:format.date format="d.m.Y">+2 days</f:format.date>}
{<f:format.date format="d.m.Y">{day.valid}</f:format.date>}

I want to solve this in the template, not in the model or the controller.

insertusernamehere
  • 23,204
  • 9
  • 87
  • 126
zoom23
  • 694
  • 2
  • 10
  • 23

4 Answers4

14

Assign your date to variable »yourdate«.

<f:if condition="{f:format.date(date: '+2 days', format: 'Y-m-d')} < {f:format.date(date: yourdate, format: 'Y-m-d')}">
    <f:then>
       yourdate is smaller than now + 2 days.
    </f:then>
    <f:else>
        yourdate is greater than or equal to now + 2 days.
    </f:else>
</f:if>
shredding
  • 5,374
  • 3
  • 46
  • 77
2

Here is my current solution which adds in a current date and does some calculations with the date from the content.

In the controller, add the current date to the data:

$this->view->assign('date_now', new \DateTime());

This is available as {date_now} in fluid then:

<f:if condition="{f:format.date(date: date_now, format: '(Y-m-d)')} > {f:format.date(date: '{event.date}-4 weeks', format: '(Y-m-d)')}">
   <f:then>
      <p>Event date is past</p>
   </f:then>
   <f:else>
      <p>Event date is upcoming</p>
   </f:else>
</f:if> 

Note how on the right side, where some calculation is done, additional quotes and curly brackets come in ('{event.date}-4 weeks').

PS I prefer the Y-m-d format to U for a date comparison, as we don't want to compare the current time – just the date.

Urs
  • 4,984
  • 7
  • 54
  • 116
1

Convert the date to an unix timestamp using format="U" and compare them. You need to add a variable which contains the comparing date.

<f:if condition="{f:format.date(date: day.valid, format: 'U')} > {f:format.date(date: date_compare, format: 'U')}">
    Date is valid
</f:if>
Merec
  • 2,751
  • 1
  • 14
  • 21
  • Depending on what is passed in, this may give you more than dates, as the timestamps will contain minutes as well. – Urs Feb 26 '15 at 10:19
  • ... so if you need to know if you're just on the next DAY, Y-m-d is more adequate – Urs Jul 12 '16 at 19:49
0

Actually: because DateTime has a getTimestamp method (http://php.net/manual/en/datetime.gettimestamp.php, since 5.3.0) which perfectly conforms to the supported getter method naming in Fluid, the following is perfectly possible. Given $date1 and $date2 are both DateTime instances assigned to the template:

<f:if condition="{date1.timestamp} < {date2.timestamp}">...</f:if>

Will compare the two dates as unix timestamp integers without the need to format the dates. So for your case, assign a $date = (new \DateTime('now'))->modify('+2 days'); from your controller action and compare to that in Fluid. Or just assign the time() timestamp and compare directly to that, skipping the DateTime usage.

Claus Due
  • 4,166
  • 11
  • 23