如何在Thymeleaf中格式化java.util.Date?遇#temporals.format报错
解决Thymeleaf中#temporals.format处理java.util.Date报错问题
我尝试用Thymeleaf格式化日期,代码如下:
<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>
其中createdDate是java.util.Date类型(实际运行时为java.sql.Timestamp),但运行时抛出以下错误:
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)
问题原因
#temporals是Thymeleaf专为Java 8+ java.time API(如LocalDateTime、ZonedDateTime等)设计的表达式工具,不支持旧的java.util.Date/java.sql.Timestamp类型,因此找不到匹配的format方法重载,触发SpEL调用异常。
解决方案
有两种可行处理方式:
方案1:替换为java.time类型(推荐)
若可修改实体类,将createdDate的类型从java.util.Date改为java.time.LocalDateTime(或其他java.time下的日期类型),原Thymeleaf表达式无需改动,#temporals.format可直接正常工作。
方案2:使用#dates表达式适配旧Date类型
若无法修改实体类,改用Thymeleaf专门处理旧java.util.Date的#dates工具类,将表达式替换为:
<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>
#dates.format方法支持java.util.Date和java.sql.Timestamp类型,完全匹配当前场景。
内容的提问来源于stack exchange,提问作者Nunyet Calçada
相关产品推荐
相关产品推荐

