2
2

More than 3 years have passed since last update.

Thymeleafの日付比較

Posted at

Thymeleafの日付比較が賢い!

と感動したので、簡潔ですが投稿させていただきます。

コード例

ControllerからModelに値を渡し、Thymeleafで表示する例です。

○○Controller.java
...

@GetMapping("/index")
public String index(Model model) {
 model.addattribute("today", "2021-8-18");
 model.addattribute("tomorrow", "2021-8-19");
 return "index.html";

...
index.html
...

<div th:if="${today gt tomorrow}">falseなので表示されない</div>
<div th:if="${today lt tomorrow}">trueなので表示される</div>

...

比較演算子で「>」とか使いたくなりますが、
Thymeleafでは以下のように書き換える必要があります。

Javaの演算子 Thymeleafの演算子
> gt
< lt
>= ge
<= le
! not
== eq
!= neq

(参考にさせていただきました!ありがとうございます!)
Thymeleafのif文で使う比較演算子の使い方

感動ポイント

String型でModelに渡しているのに、Thymeleafが日付として前後比較してくれる。賢い。

以上!

お読みいただきありがとうございましたm(_ _)m

2
2
0

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