Thymeleaf Temporals 和日期与时区 [英] Thymeleaf Temporals and dates with Timezone

查看:22
本文介绍了Thymeleaf Temporals 和日期与时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've a Spring Boot Web application using Thymeleaf as View Layer and I need to show some dates with a specific Timezone (CET = UTC+1/UTC+2).

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

The server is set for UTC and all dates are stored in my DB as datetime in UTC format too and that's fine.

现在我想在我的 HTML 页面上显示这个日期,而不是使用 UTC 格式,而是使用 Thymeleaf Temporals 在 CET 中显示,但它似乎不起作用.

Now I want to show this dates on my HTML pages not in UTC format but in CET using Thymeleaf Temporals but it seem doesn't work.

日期对象是一个 Java Instant.

The date object is a Java Instant.

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

The retrieved date from DB is (for example) 2021-02-17T16:18:21Z and is display like:

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

但我想展示它:

17/02/2021 17:18

所以我使用了:

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

但日期总是显示为UTC

But the date is always displayed as UTC

17/02/2021 16:18

Thymeleaf 的 Java8TimeDialect 已正确配置.

The Java8TimeDialect for Thymeleaf is correctly configured.

我正在使用:

Spring Boot 2.2.4
Thymeleaf 3.0.11.RELEASE

我做错了什么?

谢谢.

推荐答案

没有 Thymeleaf temporals功能,它可以为您执行时区转换.

There is no Thymeleaf temporals function which can perform that time zone conversion for you.

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

The Instant value needs to be given a time zone, not a locale (Java locales do not manipulate time zones in this way).

你可以用Java做你需要的:

You can do what you need in Java:

Instant myInstant = Instant.parse("2021-02-17T16:18:00.00Z");
ZonedDateTime myZDT = myInstant.atZone(ZoneId.of("CET"));

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

Now, you can use the following Thymeleaf snippet:

<div th:text="${#temporals.format(myZDT, 'dd/MM/yyyy HH:mm')}"></div>

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

This will generate the following in a div:

17/02/2021 17:18

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

Now the time is displayed as 17:18 instead of 16:18.

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

UPDATE: Please be sure to read the comment from OleV.V. regarding deprecated abbreviations, including the note:

不推荐使用三个字母的时区缩写,而且通常不明确,所以不要使用 ZoneId.of(CET").使用时区 ID,如 Europe/Vienna 或 Europe/San_Marino,因此采用地区/城市格式.

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

The following question may therefore be useful:

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

以及相关的代码片段:

Set<String> zoneIds = ZoneId.getAvailableZoneIds();
for (String zone : zoneIds) {
    System.out.println(zone);
}

这篇关于Thymeleaf Temporals 和日期与时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆