Formatting date in Thymeleaf
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction to Thymeleaf
Thymeleaf is a modern server-side Java template engine used for web and standalone environments. Its primary goal is to provide an elegant and highly-maintainable way of creating templates. One of the many tasks you'll find yourself handling as a web developer is formatting dates. In Thymeleaf, formatting dates can be seamless once you understand how it integrates with the Java ecosystem.
Basics of Date Formatting in Thymeleaf
Thymeleaf naturally integrates with Java’s java.time package, allowing you to leverage its powerful API for formatting and parsing dates. Additionally, you can use String.format() and other utilities provided by Thymeleaf to render dates as strings for display in your applications.
Dependencies
Before diving into date formatting, ensure you have Thymeleaf set up in your project. In a Maven project, you can add the dependency as follows:
Setting Up a Model with Date
Consider a simple Spring Boot controller that prepares a LocalDateTime object to pass to Thymeleaf:
Date Formatting in Thymeleaf Template
In your Thymeleaf template, you can format this date using the #dates utility object, which provides convenient methods for date manipulation.
With #dates.format(), you're specifying the pattern directly in the template. The method uses the pattern syntax similar to java.time.format.DateTimeFormatter.
Custom Date Formats
To define custom date formats globally, you can introduce them in a messages.properties file or define them as constants in a utility class.
Here's an example of defining a custom format in messages.properties:
Use the custom format in Thymeleaf like so:
Handling Different Locales
Sometimes, you might need to format dates based on user locale. Thymeleaf supports locale-based formatting directly via the #{} syntax for messages:
Using this method, you can format your date according to specific locale rules, as well as numbers, decimals, currencies, and more.
Summary Table
Below is a summary of key points for formatting dates in Thymeleaf:
| Feature | Description | Example Usage |
| Default Formatting | Uses #dates.format() with date pattern | th:text="${#dates.format(currentDate, 'dd MMM yyyy')}" |
| Custom Formats | Defined in properties file or utility classes | th:text="${#dates.format(currentDate, #messages['date.format.short'])}" |
| Locale-Specific Formats | Formats dates based on locale | th:text="${#dates.format(currentDate, 'dd MMM yyyy', 'fr')}" |
| Static Formats | Using hard-coded formats directly in template | th:text="${T(java.time.format.DateTimeFormatter).ofPattern('yyyy-MM-dd').format(currentDate)}" |
Additional Tips
- Using Spring's Messages: Utilize Spring's messages for reusable and localized patterns.
- Integration with Java 8 Time Package: Take advantage of Java 8's Date and Time API for more complex operations and compatibility.
- Validation and Error Handling: Ensure that you include error handling in controllers for invalid date values or parsing errors.
Conclusion
Formatting dates in Thymeleaf is intuitive once you become familiar with the tools it provides. Whether you're using predefined formats, custom formats, or dealing with locales, Thymeleaf's integration with Java's time package and utility functions ensure a seamless and powerful way to present date information in your applications. As with all aspects of software development, test your formatting with a variety of locale and date scenarios to catch edge cases and ensure robust functionality in your applications.
Related reading
- Found multiple occurrences of org.json.JSONObject on the class path
- Four color theorem Java implementation of U.S. map
- functional interface that takes nothing and returns nothing
- Functional style of Java 8's Optional.ifPresent and if-not-Present?
- GCP dataproc - java.lang.NoClassDefFoundError org/apache/kafka/common/serialization/ByteArraySerializer
- Generate Java class from JSON?
- Generate UML Class Diagram from Java Project
- Generating a Random Number between 1 and 10 Java

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.