Format Joda Time in Thymeleaf Templates and WIN

If you use Thymeleaf templates in Spring Boot and want to include your Joda Time dates, it can be annoying.

Why?

Out of the box, to format dates in a template you have to get that done ahead of time, in the controller or service.

This can cause some complexity and confusion because the way the date is displayed is not packaged with the template, which does the displaying.

Silly.

Enter a Joda Time dialect for Thymeleaf.

Example!


<span th:text="${updatedDateFormatted}" th:title="${updatedTitle}" />
 

is how we used to do it.

updatedDateFormatted and updatedTitle needed to be created ahead of time, but who wants to do that step themselves?


<span th:text="${#joda.format(updatedDate, 'MM-dd-yyyy')}"
    th:title="${#joda.format(updated, 'E')}" />
    

keeps the formatting where it belongs: in the template.

Both of these can display a formatted date with the day of the week on hover.

I'd rather use the second one.


To add this to your project, include this handy dependency in your build.gradle:


implementation `nz.net.ultraq.thymeleaf:thymeleaf-joda-dialect:2.0.0
 

for Thymeleaf 3.x

OR


implementation `nz.net.ultraq.thymeleaf:thymeleaf-joda-dialect:1.0.2
 

for Thymeleaf 2.x

Thanks for reading!

Comments powered by Talkyard.