Thymeleaf 时间和日期与时区

Yur*_*uri 2 timezone datetime thymeleaf spring-boot java-time

我有一个使用 Thymeleaf 作为视图层的 Spring Boot Web 应用程序,我需要显示一些具有特定时区的日期 (CET = UTC+1/UTC+2)。

服务器设置为 UTC,所有日期也以 UTC 格式作为日期时间存储在我的数据库中,这很好。

现在我想使用 Thymeleaf Temporals 在 HTML 页面上显示此日期,不是以 UTC 格式,而是以 CET 格式,但它似乎不起作用。

日期对象是一个 Java Instant。

从数据库检索的日期是(例如)2021-02-17T16:18:21Z并且显示如下:

<div th:text="${#temporals.format(user.lastAccess, 'dd/MM/yyyy HH:mm')}"></div>
=> 17/02/2021 16:18
Run Code Online (Sandbox Code Playgroud)

但我想像这样展示它:

17/02/2021 17:18
Run Code Online (Sandbox Code Playgroud)

所以我用了:

或者

<div th:text="${#temporals.format(user.lastAccess, 'dd/MM/yyyy HH:mm', new java.util.Locale('it', 'IT'))}"></div>
Run Code Online (Sandbox Code Playgroud)

但日期始终显示为 UTC

17/02/2021 16:18
Run Code Online (Sandbox Code Playgroud)

Thymeleaf 的配置Java8TimeDialect正确。

我在用着:

Spring Boot 2.2.4
Thymeleaf 3.0.11.RELEASE
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

谢谢。

and*_*mes 5

没有Thymeleaf 时间函数可以为您执行时区转换。

\n

Instant值需要指定时区,而不是区域设置(Java 区域设置不会以这种方式操作时区)。

\n

您可以在 Java 中执行您需要的操作:

\n
Instant myInstant = Instant.parse("2021-02-17T16:18:00.00Z");\nZonedDateTime myZDT = myInstant.atZone(ZoneId.of("CET"));\n
Run Code Online (Sandbox Code Playgroud)\n

现在,您可以使用以下 Thymeleaf 代码片段:

\n
<div th:text="${#temporals.format(myZDT, \'dd/MM/yyyy HH:mm\')}"></div>\n
Run Code Online (Sandbox Code Playgroud)\n

这将在 a 中生成以下内容div

\n
17/02/2021 17:18\n
Run Code Online (Sandbox Code Playgroud)\n

现在时间显示为17:18而不是16:18

\n
\n

更新:请务必阅读 OleV.V 的评论。关于已弃用的缩写,包括注释:

\n
\n

三字母时区缩写已被弃用,并且常常不明确,因此不要\xe2\x80\x99t 使用 ZoneId.of("CET")。使用欧洲/维也纳或欧洲/圣马力诺等时区 ID,因此采用地区/城市格式。

\n
\n

因此,以下问题可能有用:

\n

java.time 的官方区域名称列表在哪里?

\n

以及相关的代码片段:

\n
Set<String> zoneIds = ZoneId.getAvailableZoneIds();\nfor (String zone : zoneIds) {\n    System.out.println(zone);\n}\n
Run Code Online (Sandbox Code Playgroud)\n