Month localization in Thymeleaf

Viewed 377

I am writing a spring boot application using Thymeleaf as template engine.

Need to localize month translation of displayed date into Ukrainian:

Expected result 10-квітня-2021 18:58:53 is displayed after switching the language

In general localization (EN/UA) works fine.

I tried the following tips, but dates are still displayed in English after switching the language (i.e. 10-April-2021 18:58:53):

 <table class="table table-bordered table-striped ">
                <thead class="thead-dark">
                <tr>
                  ...
        
                    <th></th>
                </tr>
                </thead>
        
                <tbody>
                <tr th:each="tempReport : ${page}">
                    
                   ...
        
                    <td th:text="${#temporals.format(T(java.time.LocalDate).of(#dates.year(tempReport.reportDate),
        #dates.month(tempReport.reportDate), #dates.day(tempReport.reportDate)), 'dd-MMMM-yyyy', new java.util.Locale('ua', 'UA'))}"></td>
        
                </tr>
                </tbody>
    </table>

and this

 ...
<td th:text="${T(org.thymeleaf.util.DateUtils).monthName(#dates.createNow(), #locale)}"></td>
    ...

Also tried this code, and it works

...
        <td th:text="${T(org.thymeleaf.util.DateUtils).monthName(#dates.createNow(), #locale.GERMAN)}"></td>
...

but the problem is there is NO UKRAINIAN constant for this approach, like #locale.UKRAINIAN

My date in POJO class:

@Column(name = "report_date")
    @Temporal(TemporalType.DATE)
    @DateTimeFormat(pattern = "dd/MM/yyyy")
    @NotNull
    private Date reportDate;

Any help to resolve the issue will be appreciated!

1 Answers

When you use #locale.GERMAN that is just a convenient constant value for one of the more commonly used languages.

You can build a locale for any language using the relevant language tag. So, try #locale.forLanguageTag('uk').


WARNING:

For BCP 47 language tags (as used by Java's Locale), Ukraine (the country) is UA, but Ukrainian (the language) is uk.

You can combine them into uk-UA which is also a valid BCP 47 language tag. This means "the Ukrainian language as used in Ukraine".

That may be redundant, and you may only need uk. It's more relevant for languages like French (fr) which can be significantly different in France (FR) versus Canada (CA). So fr-CA means "Canadian French". I don't know if there are significant variations of Ukrainian used in other countries, outside of Ukraine.

If you are using the constructor:

Locale(String language, String country) 

then for your purposes, it should be this:

Locale('uk', 'UA') // this is correct

So, the WARNING is this: If you use the following:

Locale('uk', 'UK') // this is INCORRECT!

then that is incorrect - it means "the Ukrainian language as used in some unknown location represented by UK".

There is an online validator where you can test these language tags for yourself.

Related