繁体   English   中英

Spring myBatis强制将ZonedDateTime保存在系统默认时区中,如何防止?

[英]Spring myBatis forcing to save ZonedDateTime in system default timezone, how to prevent?

我正在设置一个API,该API接收日期时间为String以及日期时间来自的国家/地区。 我有一个将这些字符串转换为ZonedDateTime的格式化程序

假设我正在发送此JSON:

{
    "country": "ID",
    "activeUntil":"2020-03-10 08:00:00"
}

ID适用于印度尼西亚(时区“亚洲/雅加达” UTC + 7)

这是我的转换器

public static ZonedDateTime convertDatetimeStringToDatetime(String dtString, String country) throws ParseException {
    DateFormat formatter = new SimpleDateFormat(("yyyy-MM-dd HH:mm:ss"));
    formatter.setTimeZone(TimeZone.getTimeZone(CountryTimezones.timezoneMap.get(country)));
    return formatter.parse(dtString).toInstant().atZone(ZoneId.of(CountryTimezones.timezoneMap.get(country)));
}

CountryTimezones.getTimeZone只是将国家/地区简码链接到其时区的地图。

直到一切顺利,我的对象才拥有我想要的值。

log.info(myObject.getActiveUntil().toString());
log.info(myObject.getActiveUntil().toLocalDateTime().toString());
log.info(myObject.getActiveUntil().withZoneSameInstant(ZoneId.of("UTC")).toString());

表演

2020-03-10T08:00+07:00[Asia/Jakarta]
2020-03-10T08:00
2020-03-10T01:00Z[UTC]

当我将日期保留到数据库中时,问题就来了。 我正在使用mybatis,查询如下:

<insert id="insert">
    INSERT INTO sometable (country, active_until, created_by)
    VALUES (#{entity.country}, #{entity.activeUntil}, #{entity.createdBy})
</insert>

(为清楚起见已缩短)

保存的日期时间是“ 2020-03-10 09:00:00”

有关信息,我的位置时区为utc + 8,即日期时间已自动转换为我的位置时区。

MyBatis版本<mybatis.version>3.4.5</mybatis.version>

我正在使用MySQL DB

active_until列的类型为(MySQL)datetime。

这查询日志:

==> Preparing: INSERT INTO sometable (country, active_until, created_by) VALUES (?, ?, ?)
==> Parameters: ID(String), 2020-03-10 09:00:00.0(Timestamp), Created by System(String)

如何更改此行为以强制将我的所有ZonedDateTime保存在UTC中

我通过将其添加到Application.java中来修复它

@PostConstruct
public void init() {
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    System.out.println("Spring boot application running in UTC timezone :" + new Date());
}

myBatis显然将应用程序的时区用作保存ZonedDateTime的时区。 由于尚未设置,因此应用程序时区使用的是系统默认值,该时间必须是我所在位置的时区。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM