Search code examples
javaspringspring-bootthymeleafspring-thymeleaf

How to format Dates in Thymeleaf


I've tried this:

<p class="post-date">
                    <time datetime="2023-01-01" th:text="${#temporals.format(item.getCreatedDate(), 'dd-MM-yyyy HH:mm')}">Oct 5, 2023</time>
                  </p>

where createdDate is a java.util.Date

but I am getting this error:

2024-03-30 17:15:58.620 ERROR [] o.a.c.c.C.[.[.[.[dispatcherServlet]@log(175) - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#temporals.format(item.getCreatedDate(), 'dd-MM-yyyy HH:mm')" (template: "blog-details" - line 109, col 49)] with root cause
org.springframework.expression.spel.SpelEvaluationException: EL1004E: Method call: Method format(java.sql.Timestamp,java.lang.String) cannot be found on type org.thymeleaf.expression.Temporals
    at org.springframework.expression.spel.ast.MethodReference.findAccessorForMethod(MethodReference.java:237)
    at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:147)
    at org.springframework.expression.spel.ast.MethodReference$MethodValueRef.getValue(MethodReference.java:400)

Solution

  • How about trying this one?

    <p class="post-date">
      <time datetime="2023-01-01" th:text="${#dates.format(item.getCreatedDate(), 'dd-MM-yyyy HH:mm')}">Oct 5, 2023</time>
    </p>
    

    Explaination:

    I saw that the error said the method format of org.thymeleaf.expression.Temporals does not have the prototype of (java.sql.Timestamp, java.lang.String). So I can understand that your item.getCreatedDate() is java.sql.Timestamp class:

    package java.sql;
    
    public class Timestamp extends java.util.Date {
       ...
    }
    

    This class is extends of java.util.Date, so you can use org.thymeleaf.expression.Dates instead:

    package org.thymeleaf.expression;
    
    public final class Dates {
        public String format(final Date target, final String pattern) {
           ...
        }
    }