2016-10-04 40 views
21

Jestem nowy w Java/Spring/Thymeleaf, więc proszę o zachowanie mojego obecnego poziomu zrozumienia. Zrobiłem recenzję this similar question, ale nie udało mi się rozwiązać mojego problemu.Formatowanie daty w Thymeleaf

Próbuję uzyskać datę uproszczoną zamiast długiego formatu daty.

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

Wyjście prądowe

sprint1 2016-10-04 14:10:42.183 

Odpowiedz

41

walidacja Bean nie ma znaczenia, należy użyć Thymeleaf formatowanie:

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

także upewnić się, że nieruchomość releaseDate jest java.util.Date.

wyjściowa będzie jak: 04-Oct-2016

+5

będę po prostu zostawić to tutaj: Jeśli jesteś używając LocalDate lub LocalDateTime użyj "temporals" zamiast "dat" w Thymeleaf –

11

Jeśli chcesz użyć konwerterów w th: atrybuty tekstu, trzeba użyć składni podwójnego nawiasu.

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

(są one automatycznie stosowane do th: atrybuty pola)

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

+0

Czy istnieje sposób na skonfigurowanie formatu używanego przez konwerter podwójnych nawiasów? –

+0

@DavidTroyer działa prawie w dowolny sposób, w jaki normalnie byś to zrobił - możesz użyć '@ DateTimeFormat' (podobnie jak pytanie), możesz rozszerzyć klasę' @ Configuration' 'WebMvcConfigurerAdapter' i zastąpić addFormatters, aby dodać a 'Konwerter ', itp ... – Metroids

0

należy użyć Thymeleaf milisekund formatowaniu

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