如果您碰巧使用Spring Boot和Thymeleaf,并且需要在视图中格式化Java 8 Date&Time对象,则可以使用thymeleaf-extras-java8time
–用于Java 8 Date&Time API的Thymeleaf模块。
向现有的基于Maven或Gradle的Spring Boot项目中添加thymeleaf-extras-java8time
就像添加依赖项并使用模板引擎注册新方言一样容易。
对于Maven,将以下依赖项添加到现有的POM中:
<dependency><groupId>org.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-java8time</artifactId><version>2.1.0.RELEASE</version>
</dependency>
完成后,下一步就是将方言添加到模板引擎中。 使用Spring Boot,您需要在应用程序上下文中定义org.thymeleaf.extras.java8time.dialect.Java8TimeDialect
类型的Bean。 所有类型为org.thymeleaf.dialect.IDialect
bean org.thymeleaf.dialect.IDialect
注入到Spring Boot的ThymeleafAutoConfiguration
并自动添加到Thymeleaf的SpringTemplateEngine
。
@SpringBootApplication
public class Application {@Beanpublic Java8TimeDialect java8TimeDialect() {return new Java8TimeDialect();}public static void main(String[] args) {SpringApplication.run(Application.class);}
}
Java8TimeDialect
是,在表达式求值期间将temporals
对象作为实用程序对象添加到上下文。 这意味着它可以用于OGNL或SpringEL表达式评估:
The time is: <strong th:text="${#temporals.format(now, 'dd/MMM/yyyy HH:mm')}">31/12/2015 15:00</strong>
temporals
属性提供了许多实用的方法来使用java.time.Temporal
:格式化,访问属性和创建新对象。 有关GitHub上扩展和时temporals
本身检出项目页面的更多信息: thymeleaf-extras-java8time
注意 :Spring Boot和Thymeleaf项目设置在此博客文章中有更详细的描述: Spring Boot和Thymeleaf与Maven
- 本博客文章中使用的源代码: https : //github.com/kolorobot/spring-boot-thymeleaf
翻译自: https://www.javacodegeeks.com/2015/11/how-to-java-8-date-time-with-thymeleaf-and-spring-boot.html