Adam Perliński
Adam Perliński

Reputation: 11

Thymeleaf. How to compare if the date is from future, or past?

I want to check if the date which is in Employee.dateOfTermination is after date "now". Unfortunetely, after running following code, I get nothing on data:

<td> <div th:switch="${employee.dateOfTermination}"> 
                            <span th:case="'&lt; now'">CASE 1</span>
                            <span th:case="'&gt; now'" th:text="${#dates.format(employee.dateOfTermination, 'dd-MM-yyyy')}">CASE 2</span></div></td>

Here comes the problem, the syntax of thymeleaf does seem unappliable and disgusting for me. I tried with th:if, and parsing a int.

Upvotes: 0

Views: 9100

Answers (2)

Adi G.
Adi G.

Reputation: 21

Another option would be to insert a new parameter in the backend and pass it through to Thymeleaf. For example you insert the parameter "age" in backend and its getter returns a corresponding string based on comparison with the time now (e.g. "OLDER" or "YOUNGER"). Then you add it to the ModelView of the respective Thymeleaf page, where you can use a th:switch:

<th:block th:switch="${age}">
  <th:block th:case="OLDER">
    <span th:text="Age is older than now" style="..."></span>
  </th:block>
  <th:block th:case="YOUNGER">
   <span th:text="Age is younger than now" style="..."></span>
  </th:block>
</th:block>

Upvotes: 1

Metroids
Metroids

Reputation: 20487

I would do it like this:

<span th:if="${employee.dateOfTermination.before(#dates.createNow())}">Case 1</span>
<span th:if="${employee.dateOfTermination.after(#dates.createNow())}">Case 2</span>

Or maybe, if you do like the switch:

<div th:switch="${employee.dateOfTermination.before(#dates.createNow())}">
    <span th:case="true">Case 1</span>
    <span th:case="false">Case 2</span>
</div>

Upvotes: 5

Related Questions