How to use Dates.Format with locale in Thymeleaf
I’m trying to format a date with locale in Thymeleaf, I’ve used 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>
However, none of the above is valid.
I’m based on this problem that has been solved
https://github.com/thymeleaf/thymeleaf-extras-java8time/pull/6
Solution
I’m having the same problem as you.
It doesn’t work because you need to use #temporals
instead of #dates
.
To do this, you need to add the thymeleaf-extras-java8time dependency to your project:
compile("org.thymeleaf.extras:thymeleaf-extras-java8time:3.0.4.RELEASE")
Keep in mind that the Locale feature was added after version 2.1.0 was released, so you must use 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")
As @Andreas points out, you need to specify the entire package name, for example:
<pre class=”lang-html prettyprint-override”><td th:text="${#temporals.format(embargo.fecha, 'dd-MMMM-yyyy', new java.util.Locale('es', 'ES'))}"></td>
Also note that #temporals
does not apply to java.util.Dates, they apply to java.time.LocalDate and < strong>java.time.LocalDateTime
If you can’t change the backend to use java.time.LocalDate, one solution is to use a static method to create it from your java.util.Date 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))
Put it into your example and it will become:
<pre class=”lang-html prettyprint-override”><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 this helps!