2016-10-04 273 views
21

我是Java/Spring/Thymeleaf的新品牌,请耐心等待我目前的理解程度。我没有审查this similar question,但无法解决我的问题。在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> 

电流输出

sprint1 2016-10-04 14:10:42.183 

回答

41

Bean验证不要紧,你应该使用Thymeleaf格式:

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

另外,还要确保你releaseDate属性是java.util.Date

输出将是这样的:04-Oct-2016

+5

我就离开这个位置:如果你是使用LocalDate或LocalDateTime在Thymeleaf中使用“temporals”而不是“dates” –

11

如果你想在日使用转换器:文本属性,你必须使用双括号语法。

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

(他们会自动应用到TH:字段属性)

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

+0

有没有方法配置双括号转换器使用的格式? –

+0

@DavidTroyer它可以正常工作 - 你可以使用'@ DateTimeFormat'(就像问题一样),你可以让'@ Configuration'类扩展'WebMvcConfigurerAdapter'并覆盖addFormatters来添加一个'Converter '等等... – Metroids

0

你应该使用Thymeleaf格式毫秒

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