在Thymeleaf格式化日期

ada*_*een 41 java datetime-format thymeleaf spring-boot

我是Java/Spring/Thymeleaf的新手,所以请关注我目前的理解水平.我确实审查了这个类似的问题,但无法解决我的问题.

我想要一个简化的日期而不是长日期格式.

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

HTML:

<table>
    <tr th:each="sprint : ${sprints}">
        <td th:text="${sprint.name}"></td>
        <td th:text="${sprint.releaseDate}"></td>
    </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

电流输出

sprint1 2016-10-04 14:10:42.183
Run Code Online (Sandbox Code Playgroud)

Dim*_*San 75

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

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

还要确保你的releaseDate财产java.util.Date.

输出将如下: 04-Oct-2016

  • 我将在此处留下:如果您使用LocalDate或LocalDateTime在Thymeleaf中使用"temporals"而不是"dates" (17认同)

Met*_*ids 17

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

<td th:text="${{sprint.releaseDate}}"></td>
Run Code Online (Sandbox Code Playgroud)

(它们会自动应用于:字段属性)

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


小智 5

如果要显示示例= 20-11-2017

您可以使用:

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

  • 注意 - 时间仅支持 java 8 时间 api(不是标准 java.util.Date)。为了使用此功能,您需要添加“thymeleaf-extras-java8time”依赖项。 (5认同)
  • `spring-boot-starter-thymeleaf` 已经包含 `thymeleaf-extras-java8time`。 (4认同)