let me down slowly
let me down slowly

Reputation: 1017

@DateTimeFormat pattern or jackson date-format in spring mvc not working

I have a Spring MVC app. I have the following pattern set to my entity:

@Entity
public class Test {
    @CreationTimestamp
    @DateTimeFormat(pattern = "MM-dd-yyyy")
    private Timestamp createdTime;

In my application.property I have this line:

spring.jackson.date-format=yyyy-MM-dd hh:mm:ss aa

I am showing the date from thymeleaf as follows:

<tr th:each="problem : ${test}">
  <td th:text="${problem.id}" />
  <td th:text="${problem.createdTime}" />
  ...
</tr>

But it is showing this format from html and on Postgresql select regardless of pattern specified in @Datetimeformat annotation:

2021-06-26 16:27:29.105

I want datetime to be shown in this format from html:

2021-06-26 04:27:29 PM

How can I do this? It would be better if I could just change it from the application.property file since I have many other Timestamp columns and I don't want to change each file. Thank you.

Upvotes: 0

Views: 709

Answers (2)

ThilankaD
ThilankaD

Reputation: 1099

you can read the dateTime format from the application.properties file and pass that as the date format to the Thymeleaf's #dates util, so you don't need to do any changes in entity level and can control the DateTime parse through single place.

<tr th:each="problem : ${test}">
  <td th:text="${problem.id}" />
  <td th:text="${#dates.format(problem.createdTime,@environment.getProperty('spring.jackson.date-format'))}" />
  ...
</tr>

Upvotes: 1

Alex Chernyshev
Alex Chernyshev

Reputation: 1745

You're using Thymeleaf template engine, so try this:

<td th:text="${#dates.format(problem.createdTime,'MM-dd-yyyy hh:mm:ss aa'}" />
                    

Upvotes: 1

Related Questions