【发布时间】:2019-12-31 05:03:12
【问题描述】:
我正在设置一个 API,它以字符串形式接收日期时间以及日期时间所在的国家/地区。我有一个格式化程序,可以将这些字符串转换为 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 数据库
active_until 列的类型是(MySQL)日期时间。
这是查询日志:
==> 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
【问题讨论】:
-
请指定 1) MyBatis 版本,2) DB/驱动程序版本和 3)
active_until列的类型。 -
我将编辑我的帖子。
3.4.5 MySQL DBactive_until属于 Mysqldatetime类型
标签: java spring datetime timezone mybatis