Thymeleaf is a template engine based on Java created for processing XHTML, XML, JS, CSS, and other web documents. Thymeleaf comes with lots of features. In this article, we are going to present utility methods used for processing dates.
2. Maven dependencies
Let's start with maven dependencies required for Thymeleaf projects. Thymeleaf is mainly used with Spring and Spring Boot applications so our dependencies consider that kind of configuration.
We need the following dependencies to start using Thymeleaf in Spring Boot applications:
To start working with new Java 8 Date classes, we will add the following dependency to our pom.xml:
The latest versions of the above dependencies could be found using the following links:
To present how new and old utility methods for processing date works we created a simple Spring Controller class that will serve date.html template on the root context. We also add several variables to our template model to have some example dates ready to process and format.
4. Processing dates with #dates and #temporals utility classes
Thymeleaf comes with many extra features that could be added to our project by simply using special maven dependencies. Additional extras are created and supported by the Thymeleaf team to be compatible with the newest versions of Java.
By adding thymeleaf-extras-java8time dependency we can start using Java 8 Time API right away. The new utility class #temporals will appear in context and it will be available to use in Thymeleaf expressions.
To test utility methods we use the following Thymeleaf template:
This is the final result we'll see in the browser:
To work with LocalDateTime, LocalDate and Instant we need to use #temporals utility. For standard Dates there is built-in #dates utility available without additional dependencies.
Notice we could display date using specific locale, for example below piece of HTML:
will be rendered to:
It is important to remember that in order to work with time parts we need to have an object that supports time like for example LocalDateTime.
The following expression will try to get a SecondOfMinute part of the LocalDate object that does not support the time:
This will cause the following exception in runtime:
5. Conclusion
In this article, we presented date processing methods using Thymeleaf utility classes. For objects presented in Java 8 like LocalDate, LocalDateTime, Instant we need to add special dependency thymeleaf-extras-java8time that include #temporals utility ready to be used in the Thymeleaf templates.
The code used in this tutorial can be found in the GitHub project.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}