【问题标题】:@DateTimeFormat pattern or jackson date-format in spring mvc not workingspring mvc中的@DateTimeFormat模式或jackson日期格式不起作用
【发布时间】:2021-06-26 10:35:53
【问题描述】:

我有一个 Spring MVC 应用程序。我为我的实体设置了以下模式:

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

在我的application.property 我有这行:

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

我正在显示来自 thymeleaf 的日期如下:

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

但无论@Datetimeformat 注释中指定的模式如何,它都从 html 和 Postgresql 选择显示这种格式:

2021-06-26 16:27:29.105

我希望从 html 中以这种格式显示日期时间:

2021-06-26 04:27:29 PM

我该怎么做?如果我可以从 application.property 文件中更改它会更好,因为我有许多其他 Timestamp 列并且我不想更改每个文件。谢谢。

【问题讨论】:

  • 你能分享一个 Github 链接以获取示例吗?这样我就可以在本地机器上轻松调试了

标签: java spring thymeleaf


【解决方案1】:

您可以从 application.properties 文件中读取 dateTime 格式,并将其作为日期格式传递给 Thymeleaf 的 #dates util,因此您无需在实体级别进行任何更改,并且可以通过控制 DateTime 解析一个地方。

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

【讨论】:

    【解决方案2】:

    你正在使用 Thymeleaf 模板引擎,所以试试这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 2016-04-11
      • 2018-08-14
      • 2016-01-17
      • 2018-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多