在Thymeleaf中格式化日期

60

我刚接触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;
}

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
6个回答

114

Bean验证并不重要,您应该使用Thymeleaf格式化:

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

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

输出将类似于:04-Oct-2016


43
如果您正在使用LocalDate或者LocalDateTime,请在Thymeleaf中使用"temporals"而不是"dates"。 - Joaquín L. Robles
另外,如果您想指定自定义的Locale,则必须将其引用为OGNL表达式(https://commons.apache.org/proper/commons-ognl/language-guide.html)。例如,`new java.util.Locale('en', 'US')@java.util.Locale@ENGLISH`。 - cbreezier

24

有没有一种方法可以配置双括号转换器使用的格式? - David T
1
@DavidTroyer 它可以与通常使用的任何方式配合使用 - 您可以使用 @DateTimeFormat(就像问题中一样),您可以让您的 @Configuration 类扩展 WebMvcConfigurerAdapter 并重写 addFormatters 来添加 Converter <Date,String> 等等... - Metroids
国际化的好答案。视图不依赖于区域设置。 - riddle_me_this
与日期(Date)完美配合,但与本地日期时间(LocalDateTime)不兼容。你能帮忙吗? - Yura Shinkarev

18

如果您想展示例如20-11-2017的日期,您可以使用:

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

7
注意:temporals仅支持Java 8时间API(不支持标准的java.util.Date)。为了使用此功能,您需要添加thymeleaf-extras-java8time依赖。 - Michał Stochmal
4
spring-boot-starter-thymeleaf 已经包含了 thymeleaf-extras-java8time - Pavel Alay

3

您应该使用Thymeleaf格式化毫秒

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

3

关于依赖项:

<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>

如果您将使用Java 8的新日期包中的LocalDateLocalDateTime或其他任何类,则应添加此附加依赖项。

<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>

这篇文章也许可以帮助您更深入地了解Thymeleaf中的日期

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接