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
相关产品推荐
相关产品推荐

