Thymeleaf same date format in th:text and th:field

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Thymeleaf same date format in th:text and th:field

yongo
Hi,

I have an entity which contains a date field, 'validFrom'. I want to display the date 2 times, once in a table where the date is readonly, once in an input field where the date can be set. My problem is that I cannot figure out how to correctly display the date in both cases using the client Locale, which uses this format: dd.MM.yyyy

Here is the jpa entity (irrelevant annotations left out):

    public class Category {
   
    @javax.persistence.Temporal(TemporalType.DATE)
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private java.sql.Date validFrom;
   
        ....
   
    }

Here is the table displaying the entities:
<... th:each="item: ${allItems}">
    <... th:text="${{item.validFrom}}">

(I had to remove the html tags so it would be displayed in this forum)

Here is the page where the user can create the entity and enter the date:

    <form th:action="@{/categories/edit}" th:object="${entity}" method="post">
        <input type="date" th:field="*{validFrom}"/>

With this configuration I get the correct format (dd.MM.yyyy) in the input field but the wrong format in the text field (yyyy-MM-dd).

When I change the annotation in the entity to

    @DateTimeFormat(pattern = "dd.MM.yyyy")

I get the correct format in the text field, but the input field remains empty with the following error message in my browser console:

The specified value "18.05.2018" does not conform to the required format, "yyyy-MM-dd".

The last thing I tried is approach one using thymeleaf's #dates.format(date) in the text field. Unfortunately this also appends HH:MM:SS, which I don't want.

Now I could of course pass the format 'dd.MM.yyyy' as second parameter but then it's hardcoded into my html which blows i18n. So I tried to pass #{date.format}, which I specified in my messages.properties but this caused a parsing error:

Expression [#dates.format(item.validFrom, #{date.format})] @31: EL1043E: Unexpected token. Expected 'identifier' but was 'lcurly({)'

How to solve this?

PS: I also posted this question at stackoverflow: https://stackoverflow.com/questions/50410685/thymeleaf-same-date-format-in-thtext-and-thfield