Search code examples
javaspring-bootthymeleaf

spring boot thymeleaf format date gives "Cannot retrieve hour from null"


I have a spring boot application in which I am trying to display date of birth in a formatted manner. If i don't use the thymeleaf dates format option i was able to display the date but if use the format option it gives me the "Cannot apply format on null".

 <td th:text="*{dateOfBirth}">06/23/2013</td>
 output: 1990-01-21 00:03:00.0

 <td th:text="${#dates.format(dateOfBirth,'dd-mm-yyyy')}">06/23/2013</td>
 output ::Cannot apply format on null

the dateOfBirth field in my pogo class is declared as below.

@JsonDeserialize(using = CustomeDateDeserializer.class)
@DateTimeFormat(pattern="dd-mm-yyyy")
private Date dateOfBirth;

I have tried with difference combinations but all giving me the same error. Can any one help me what I am missing in here.


Solution

  • *{dateOfBirth} has a specific meaning. When you use the * notation, you are referring to a property of the th:object you have selected. When you use a ${} expression, you lose that. In order to specify the same variable, you should use the #object expression variable (or name the complete path to the variable in question).

    <td th:text="${#dates.format(#object.dateOfBirth,'dd-MM-yyyy')}">06/23/2013</td>
    

    Note: Since you are already specifying the date format of your variable, I think that the double-bracket syntax should work for you:

    <td th:text="${{#object.dateOfBirth}}">06/23/2013</td>