ThymeleafでLocalDateTimeを扱う

Javaのjava.timeのライブラリでLocalDateTime便利なのですが、Thymeleaf3系では対応していません。

thymeleaf-extras-java8timeというライブラリを追加すると、使用できるようになります。本記事ではThymeleaf3系でLocalDateTimeを使用する方法をご紹介します。

Java側ソースコード

SampleController.java
package com.example.demo;

import java.time.LocalDateTime;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class SampleController {

  @GetMapping(value = "/")
  public String sampleHostGet(Model model) {

    // 現在時刻を設定して返却
    model.addAttribute("serverTime", LocalDateTime.now());
    return "index";
  }

}

LocalDateTimeの詳細な仕様方法は次の記事を記載があります。

JavaのLocalDateTimeで日時関連処理を簡単にする方法
Javaで日時関連の処理を対応するにはjava.timeのライブラリでLocalDateTimeが便利です。これらはJava8から対応されま...

thymeleaf用ライブラリ追加

dependenciesにライブラリを追加します。

Gradle

build.gradle
dependencies {
  compile('org.thymeleaf.extras:thymeleaf-extras-java8time:3.0.4.RELEASE')
}

Spring Bootでは次のように記述することが出来ます。

build.gradle
dependencies {
  implementation 'org.thymeleaf.extras:thymeleaf-extras-java8time'
}

Spring Bootを使用している場合は、Spring Boot側で適切なバージョンを使用してくれるため、こちらを使用する方が良いです。

Maven

pom.xml
<dependency>
  <groupId>org.thymeleaf.extras</groupId>
  <artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>

Thymeleaf側ソースコード

index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
  </head>
  <body>
    <p th:text="${#temporals.format(serverTime, 'yyyy/MM/dd HH:mm:ss')}"></p>
  </body>
</html>

結果

Webブラウザにこのように出力されます。

2021/01/09 23:45:59

参考

thymeleaf/thymeleaf-extras-java8time – github