You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot日期时间存储异常及巴西格式适配解决方案

Spring Boot 日期时间存储时区异常及解决方法

问题场景

本地时间为2023-03-21 23:03,但数据库存储的时间却变成了2023-03-22 01:44:05.073000,同时需要将日期转为巴西格式dd/MM/yyyy。

原实现代码:

@Temporal(TemporalType.TIMESTAMP)
@JsonProperty("datebuy")
private Date datebuy;

p.setDatebuy(new Date(System.currentTimeMillis()));

问题原因

核心问题是未指定巴西时区,原代码使用的Date类默认依赖系统时区,若服务器时区与巴西圣保罗时区不一致,就会导致存储的时间出现偏移。

解决方案

改用Java 8+提供的LocalDateTime(线程安全、更易维护的日期API),并明确指定巴西圣保罗时区,同时通过DateTimeFormatter实现格式转换:

@Column(nullable = true, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
@JsonProperty("datebuy")
private LocalDateTime datebuy;

// 设置巴西圣保罗时区的当前时间
p.setDatebuy(LocalDateTime.now(ZoneId.of("America/Sao_Paulo")));

// 格式化为巴西指定格式
CartPurchaseMongo catmongo = new CartPurchaseMongo();            
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
String agoraFormatado = keyp.getDatebuy().format(formatter);

关键说明

  • LocalDateTime.now(ZoneId.of("America/Sao_Paulo")):直接获取巴西时区的当前时间,从根源避免时区偏移问题
  • DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"):按照巴西常用的日期格式完成格式化,满足业务展示需求

内容的提问来源于stack exchange,提问作者Rafael Souza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 05:32:45