Java
Thymeleaf
Date Formatting
Spring Framework
Web Development

Formatting date in Thymeleaf

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

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:

xml
1<dependency>
2    <groupId>org.springframework.boot</groupId>
3    <artifactId>spring-boot-starter-thymeleaf</artifactId>
4</dependency>

Setting Up a Model with Date

Consider a simple Spring Boot controller that prepares a LocalDateTime object to pass to Thymeleaf:

java
1import org.springframework.stereotype.Controller;
2import org.springframework.ui.Model;
3import org.springframework.web.bind.annotation.GetMapping;
4import java.time.LocalDateTime;
5
6@Controller
7public class DateController {
8
9    @GetMapping("/current-date")
10    public String showCurrentDate(Model model) {
11        LocalDateTime now = LocalDateTime.now();
12        model.addAttribute("currentDate", now);
13        return "dateView";
14    }
15}

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.

html
1<!DOCTYPE html>
2<html xmlns:th="http://www.thymeleaf.org">
3<head>
4    <title>Date Formatting</title>
5</head>
6<body>
7    <h1>Date Formatting Example</h1>
8    <p th:text="${#dates.format(currentDate, 'dd MMMM yyyy, HH:mm:ss')}">
9        Date will be displayed here.
10    </p>
11</body>
12</html>

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:

 
date.format.long=dd MMMM yyyy, HH:mm:ss
date.format.short=dd/MM/yyyy

Use the custom format in Thymeleaf like so:

html
<p th:text="${#dates.format(currentDate, #messages['date.format.long'])}">
    Custom Date Format
</p>

Handling Different Locales

Sometimes, you might need to format dates based on user locale. Thymeleaf supports locale-based formatting directly via the #&#123;&#125; syntax for messages:

html
<p th:text="${#dates.format(currentDate, 'dd MMMM yyyy', 'fr')}">
    Date in French Locale
</p>

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:

FeatureDescriptionExample Usage
Default FormattingUses #dates.format() with date patternth:text="$&#123;#dates.format(currentDate, 'dd MMM yyyy')&#125;"
Custom FormatsDefined in properties file or utility classesth:text="$&#123;#dates.format(currentDate, #messages['date.format.short'])&#125;"
Locale-Specific FormatsFormats dates based on localeth:text="$&#123;#dates.format(currentDate, 'dd MMM yyyy', 'fr')&#125;"
Static FormatsUsing hard-coded formats directly in templateth:text="$&#123;T(java.time.format.DateTimeFormatter).ofPattern('yyyy-MM-dd').format(currentDate)&#125;"

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.


Course illustration
Course illustration

All Rights Reserved.