Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting date in Thymeleaf

I'm brand new to Java/Spring/Thymeleaf so please bear with my current level of understanding. I did review this similar question, but wasn't able to solve my problem.

I'm trying to get a simplified date instead of the long date format.

// DateTimeFormat annotation on the method that's calling the DB to get date. @DateTimeFormat(pattern="dd-MMM-YYYY") public Date getReleaseDate() {     return releaseDate; } 

​ html:

<table>     <tr th:each="sprint : ${sprints}">         <td th:text="${sprint.name}"></td>         <td th:text="${sprint.releaseDate}"></td>     </tr> </table> 

Current output

sprint1 2016-10-04 14:10:42.183 
like image 649
adam.shaleen Avatar asked Oct 04 '16 19:10

adam.shaleen


People also ask

How do I convert a date to a string in Thymeleaf?

By Default thymeleaf uses the toString() method for object to String conversion. So you can safely print date if you don't mind the default formatting from Date. toString() method.

How do you set a variable in Thymeleaf?

We can use the th:with attribute to declare local variables in Thymeleaf templates. A local variable in Thymeleaf is only available for evaluation on all children inside the bounds of the HTML tag that declares it.


2 Answers

Bean validation doesn't matter, you should use Thymeleaf formatting:

<td th:text="${#dates.format(sprint.releaseDate, 'dd-MMM-yyyy')}"></td> 

Also make sure your releaseDate property is java.util.Date.

Output will be like: 04-Oct-2016

like image 137
DimaSan Avatar answered Sep 28 '22 13:09

DimaSan


If you want to use converters in th:text attributes, you have to use double-bracket syntax.

<td th:text="${{sprint.releaseDate}}"></td> 

(They are automatically applied to th:field attributes)

http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#double-bracket-syntax

like image 34
Metroids Avatar answered Sep 28 '22 11:09

Metroids