Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 427
Julian Solarte Avatar asked Sep 12 '25 03:09

Julian Solarte


1 Answers

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!

like image 101
sebasira Avatar answered Sep 14 '25 18:09

sebasira