Thymeleaf 如何支持java8的时间LocalDate和LocalDatetime

一、添加依赖

<dependency>

    <groupId>org.thymeleaf.extras</groupId>

    <artifactId>thymeleaf-extras-java8time</artifactId>

    <version>3.0.0.RELEASE</version>

</dependency>

 

 

二、测试model

  对比新老时间用法,也就是java.util and java.time这两个包的时间处理差别。

model.addAttribute("standardDate", new Date()); 
model.addAttribute("localDateTime", LocalDateTime.now());
model.addAttribute("localDate", LocalDate.now());
model.addAttribute("timestamp", Instant.now());

 

三、格式化日期,使用ISO8601 format

<h1>Format ISO</h1>

<p th:text="${#dates.formatISO(standardDate)}"></p>

<p th:text="${#temporals.formatISO(localDateTime)}"></p>

<p th:text="${#temporals.formatISO(localDate)}"></p>

<p th:text="${#temporals.formatISO(timestamp)}"></p>

 

输出:

 

四、手动指定日期格式

<h1>Format manually</h1>

<p th:text="${#dates.format(standardDate, 'dd-MM-yyyy HH:mm')}"></p>

<p th:text="${#temporals.format(localDateTime, 'dd-MM-yyyy HH:mm')}"></p>

<p th:text="${#temporals.format(localDate, 'MM-yyyy')}"></p>

 

输出:

 

 

五、获取特定日期字段和属性

java.util.Date class中使用:

${#dates.day(date)}

${#dates.month(date)}

${#dates.monthName(date)}

${#dates.monthNameShort(date)}

${#dates.year(date)}

${#dates.dayOfWeek(date)}

${#dates.dayOfWeekName(date)}

${#dates.dayOfWeekNameShort(date)}

${#dates.hour(date)}

${#dates.minute(date)}

${#dates.second(date)}

${#dates.millisecond(date)}

 

在java8的java.time中使用:

${#temporals.day(date)}

${#temporals.month(date)}

${#temporals.monthName(date)}

${#temporals.monthNameShort(date)}

${#temporals.year(date)}

${#temporals.dayOfWeek(date)}

${#temporals.dayOfWeekName(date)}

${#temporals.dayOfWeekNameShort(date)}

${#temporals.hour(date)}

${#temporals.minute(date)}

${#temporals.second(date)}

${#temporals.millisecond(date)}

 

用法:

<h1>Show only which day of a week</h1>

<p th:text="${#dates.day(standardDate)}"></p>

<p th:text="${#temporals.day(localDateTime)}"></p>

<p th:text="${#temporals.day(localDate)}"></p>

 

 

<h1>Show the name of the week day</h1>

<p th:text="${#dates.dayOfWeekName(standardDate)}"></p>

<p th:text="${#temporals.dayOfWeekName(localDateTime)}"></p>

<p th:text="${#temporals.dayOfWeekName(localDate)}"></p>

 

<h1>Show the second of the day</h1>

<p th:text="${#dates.second(standardDate)}"></p>

<p th:text="${#temporals.second(localDateTime)}"></p>

 

 

 

 


posted @ 2018-07-26 11:10  我是属车的  阅读(5560)  评论(0编辑  收藏  举报