NoHoney_k1ll
NoHoney_k1ll

Reputation: 251

thymeleaf date format while each

I'm trying to apply dates.format while I do a forEach in thymeleaf. But I get this message

org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating OGNL expression: "e.datesCoordinates.created" (template: "templates/alarms" - line 262, col 48)

If I do it outside an "th:each" It works perfectly. How can I make it work?

<div class="content" th:each="e : ${events}">
                            <div class="info date" th:value="${e.datesCoordinates.created}? ${#dates.format(e.datesCoordinates.created, 'dd/MM/yyyy HH:mm')}"></div>
                            <div class="info operator" th:text="|${e.owner.first_name} ${e.owner.last_name}|"></div>
                        </div>

Upvotes: 1

Views: 886

Answers (1)

Alain Cruz
Alain Cruz

Reputation: 5097

Since e.datesCoordinates.created is a String, you would need to parse it first, and then, you can format it. The following code should work.

<th:block th:with="sdf = ${new java.text.SimpleDateFormat('dd/MM/yyyy HH:mm')}">      
    <div class="content" th:each="e : ${events}">
        <div class="info date" th:value="${e.datesCoordinates.created}? ${#dates.format(sdf.parse(e.datesCoordinates.created), 'dd/MM/yyyy HH:mm')}"></div>
        <div class="info operator" th:text="|${e.owner.first_name} ${e.owner.last_name}|"></div>
    </div>
</th:block>

Important

When using new java.text.SimpleDateFormat you need to match the expression just like the current string format. For example, if you are saving like 10-03-2018, then your code would look like this ${new java.text.SimpleDateFormat('dd-MM-yyyy')}.

Upvotes: 1

Related Questions