Julian Solarte
Julian Solarte

Reputation: 585

How to use Dates.Format with locale in Thymeleaf

I'm trying to format a date with locale in Thymeleaf, I already used the dates.format

<td th:text="${#dates.format(embargo.fecha, 'dd-MMMM-yyyy', new Locale('es'))}"></td>

<td th:text="${#dates.format(embargo.fecha, 'dd-MMMM-yyyy',${ new Locale('es')})}"></td>

but none of above works.

I was based in this issue that is already solved https://github.com/thymeleaf/thymeleaf-extras-java8time/pull/6

Upvotes: 4

Views: 6629

Answers (2)

sebasira
sebasira

Reputation: 1834

I stumble upon the same problem as you.

The reason is not working is because you need to use #temporals instead of #dates.

In order to do that, you need to add to your project the thymeleaf-extras-java8time dependency:

compile("org.thymeleaf.extras:thymeleaf-extras-java8time:3.0.4.RELEASE")

Keep in mind that the Locale feature was added after the release of version 2.1.0 so you MUST be using Thymeleaf 3. Add:

compile("org.thymeleaf:thymeleaf-spring4:3.0.6.RELEASE")
compile("org.thymeleaf:thymeleaf:3.0.6.RELEASE")
compile("nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect:2.2.2")

And as @Andreas pointed out, you need to specify the whole package name, for example:

<td th:text="${#temporals.format(embargo.fecha, 'dd-MMMM-yyyy', new java.util.Locale('es', 'ES'))}"></td>

Also notice that the #temporals does not work with java.util.Dates and they do with java.time.LocalDate and java.time.LocalDateTime

If you can not change your backend to use java.time.LocalDate a solution would be to create it from you java.util.Date, using the static method of(year, month, day) from the LocalDate class.

For example:

T(java.time.LocalDate).of(#dates.year(embargo.fecha), #dates.month(embargo.fecha), #dates.day(embargo.fecha))

Putting that inside your example, it would become:

<td th:text="${#temporals.format(T(java.time.LocalDate).of(#dates.year(embargo.fecha), #dates.month(embargo.fecha), #dates.day(embargo.fecha)), 'dd-MMMM-yyyy', new java.util.Locale('es', 'ES'))}"></td>

Hope it helps!

Upvotes: 3

Andreas
Andreas

Reputation: 159114

Since you're using Thymeleaf with Spring Boot, the expressions are SpEL (Spring Expression Language), and the documentation says:

You can invoke constructors by using the new operator. You should use the fully qualified class name for all but the primitive types (int, float, and so on) and String.

So, you need to use new java.util.Locale('es') instead of just new Locale('es')

Upvotes: 1

Related Questions