LoginSignup
6
8

More than 5 years have passed since last update.

Thymeleaf with SpringBootでJava8の日時APIを扱う

Last updated at Posted at 2017-01-09

概要

ThymeleafにはJava8の日時APIを操作するUtilityがデフォルトで組み込まれていません。
thymeleaf-extras-java8time を組み込んで使用できるようにします。

java.util.Datejava.util.Calendar#dates#calendars がデフォルトで提供されている

前提

  • thymeleaf3
  • spring-boot1.4
  • maven3

pom.xmlの修正

thymeleaf-extras-java8time のdependencyを追加します。

<dependency>
  <groupId>org.thymeleaf.extras</groupId>
  <artifactId>thymeleaf-extras-java8time</artifactId>
  <version>3.0.0.RELEASE</version>
</dependency>

DialectをDIコンテナへ登録

※spring-boot1.4.0からDialectをDIコンテナへ登録する設定は不要になりました※

SpringBootで利用可能にするには、DialectをDIコンテナへ登録しておく必要があります。
専用のConfigurationを作って登録しておく例を書いておきます。

@Configuration
public class ThymeleafExtrasConfiguration {
    @Bean
    public Java8TimeDialect java8TimeDialect() {
        return new Java8TimeDialect();
    }
}

テンプレートでの呼び出し

下記のように呼び出せるようになります。

${#temporals.format(hogeDateTime, 'dd/MMM/yyyy HH:mm')}

まとめ

  1. dependencyを追加する
  2. DialectをDIコンテナに登録する
  3. テンプレートで使用する

参考

6
8
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8