在 Thymeleaf 中格式化日期

Formatting date in Thymeleaf

我是 Java/Spring/Thymeleaf 的新手,所以请原谅我目前的理解水平。我确实查看了 this similar question,但无法解决我的问题。

我正在尝试获取简化日期而不是长日期格式。

// DateTimeFormat annotation on the method that's calling the DB to get date.
@DateTimeFormat(pattern="dd-MMM-YYYY")
public Date getReleaseDate() {
    return releaseDate;
}

html:

<table>
    <tr th:each="sprint : ${sprints}">
        <td th:text="${sprint.name}"></td>
        <td th:text="${sprint.releaseDate}"></td>
    </tr>
</table>

当前输出

sprint1 2016-10-04 14:10:42.183

Bean 验证无关紧要,您应该使用 Thymeleaf 格式:

<td th:text="${#dates.format(sprint.releaseDate, 'dd-MMM-yyyy')}"></td>

还要确保您的 releaseDate 属性 是 java.util.Date

输出如下:04-Oct-2016

如果要在 th:text 属性中使用转换器,则必须使用双括号语法。

<td th:text="${{sprint.releaseDate}}"></td>

(它们会自动应用于 th:field 属性)

http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#double-bracket-syntax

你应该使用 Thymeleaf 格式化毫秒

<td th:text="${#dates.format(new java.util.Date(transaction.documentDate), 'dd-MMM-yy')}"></td>

如果你想展示示例 = 20-11-2017

您可以使用:

 th:text="${#temporals.format(notice.date,'dd-MM-yyyy')}

th:text="${#calendars.format(store.someDate(),'dd MMMM yyyy')}"

API : https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#calendars

关于依赖关系,

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>3.0.12.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
    <version>3.0.12.RELEASE</version>
</dependency>

如果您将使用 LocalDateLocalDateTime 或新的 Java 8 Date 包的任何其他 class,那么您应该添加此附加依赖项,

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>

关于你的日期对象的类型,如果你使用Date

<td th:text="${#dates.format(sprint.releaseDate, 'dd-MM-yyyy HH:mm')}">30-12-2021 23:59</td>

如果您使用LocalDateLocalDateTime

<td th:text="${#temporals.format(sprint.releaseDate, 'dd-MM-yyyy HH:mm')}">30-12-2021 23:59</td>

在模型属性中始终可以选择传递 DateTimeFormatter 的对象

// Inside your controller
context.setVariable("df", DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm"));
// or
model.addAttribute("df", DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm"));

// Then, in your template
<td th:text="${df.format(sprint.releaseDate)}">30-12-2021 23:59</td>

This article 可能会进一步帮助您。