Spring Boot Thymeleaf 格式化 OffsetDateTime 时区问题

Thymeleaf Spring Boot About 871 words

现象

Spring BootPostgreSQL中定时读取数据,createdAt字段是timestamptz类型。

使用Thymeleaf格式化时,如果是Asia/Shanghai+8)时区,那么对于createdAt在早晨8点前的数据,会显示为前一天。

原因

PostgreSQL中的timestamptz类型映射到Java中的是OffsetDateTime,且OffsetDateTime的时区会一直为零时区。

如果数据从PG中直接读取后渲染,在MVCController中返回给用户,Spring Boot会自动转换。

但是:由于我们的数据是定时更新,所以是暂存在Java内存中,Thymeleaf中的页面的指定部分是读取的这块缓存在内存的数据,所以此时内存中的createdAt都是零时区的OffsetDateTime

解决

使用#temporals.format指定时区的方法。

#temporals.format(post.createTs, 'yyyy-MM-dd', T(java.time.ZoneId).of('GMT+8'))

源码

public final class Temporals {

    public String format(final Temporal target, final String pattern) {
        return this.temporalFormattingUtils.format(target, pattern, (ZoneId)null);
    }

    public String format(final Temporal target, final String pattern, final String zoneId) {
        return this.temporalFormattingUtils.format(target, pattern, ZoneId.of(zoneId));
    }
    
}
Views: 18 · Posted: 2026-01-18

———         Thanks for Reading         ———

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓
Prev Post
Today In History
Browsing Refresh