LoginSignup
2
2

More than 3 years have passed since last update.

Thymeleaf でタイムゾーンを指定して現在日時を取得する

Last updated at Posted at 2019-09-14

Expression Utility Objects #calendars

Expression Utility Objects (式ユーティリティオブジェクト) の #calendars を使う。

Tutorial: Using Thymeleaf (ja) - 19 Appendix B:式ユーティリティーオブジェクト - カレンダー

/*
 * 現在日時のカレンダーオブジェクト(java.util.Calendar)を作成します
 */
${#calendars.createNow()}

${#calendars.createNowForTimeZone()}

サンプルコード

テンプレートHTMLを用意。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>

<!-- #calendars.createNow() -->
<p th:text="${#calendars.format(#calendars.createNow(), 'yyyy年MM月dd日 HH時mm分ss秒')}"></p>

<!-- #calendars.createNowForTimeZone('UTC') -->
<p th:text="${#calendars.format(#calendars.createNowForTimeZone('UTC'), 'yyyy年MM月dd日 HH時mm分ss秒')}"></p>

<!-- #calendars.createNowForTimeZone('Asia/Tokyo') -->
<p th:text="${#calendars.format(#calendars.createNowForTimeZone('Asia/Tokyo'), 'yyyy年MM月dd日 HH時mm分ss秒')}"></p>

<!-- #calendars.createNowForTimeZone('GMT+0900') -->
<p th:text="${#calendars.format(#calendars.createNowForTimeZone('GMT+0900'), 'yyyy年MM月dd日 HH時mm分ss秒')}"></p>

</body>
</html>

タイムゾーンおよびロケールが日本・日本語の環境で実行

  • #calendars.createNow()、'Asia/Tokyo'、'GMT+0900' は日本標準時で出力される
  • 'UTC' は協定世界時で出力される (日本より9時間前になる)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>

<!-- #calendars.createNow() -->
<p>2019年09月14日 09時01分23秒</p>

<!-- #calendars.createNowForTimeZone('UTC') -->
<p>2019年09月14日 00時01分23秒</p>

<!-- #calendars.createNowForTimeZone('Asia/Tokyo') -->
<p>2019年09月14日 09時00分23秒</p>

<!-- #calendars.createNowForTimeZone('GMT+0900') -->
<p>2019年09月14日 09時00分23秒</p>

</body>
</html>

今回の環境

  • OpenJDK 11.0.2
  • Thymeleaf 3.0.11

参考資料

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