插入后一小时后的日期时间.日光节约



我注意到,当我插入某些日期到我的表时,我的MySql数据库从我的DateTime对象中减去一个小时。例子:

Insert: 2021-03-29 11:44:14.938
Result: 2021-03-29 10:44:14.938

我正在使用JdbcTemplate.update:

插入Java.Sql.Timestamp对象(timestamp下面)
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement stmt = con.prepareStatement(
"INSERT INTO Table (date) VALUES (?)");
stmt.setTimestamp(5,timestamp));
return stmt;
}
});

这只发生在2021年3月28日/之后的日期时间(这是英国的夏令时)。如果我在3月28日之前插入,没有时间浪费。例子:

Insert: 2021-03-26 11:44:14.938
Result: 2021-03-26 11:44:14.938

我已经尝试使用时间戳而不是DateTime作为MySQL类型,但它没有效果。

有人知道如何阻止这种行为吗?

不确定为什么会发生这种情况,但我通过放弃Java.Sql.Timestamp以支持Java.Time.LocalDateTime来解决这个问题。

我的插入代码现在看起来像下面(其中localDateTime的类型是localDateTime而不是时间戳):

jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement stmt = con.prepareStatement(
"INSERT INTO Table (date) VALUES (?)");
stmt.setObject(5,localDateTime));
return stmt;
}
});

MySql数据库不再自动调整时区

您可以使用OffsetDateTime。从JDBC 4.2开始,您可以直接使用java.time类型:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
OffsetDateTime odt = LocalDateTime.parse("2021-03-29 11:44:14.938", dtf)
.atZone(ZoneId.of("Europe/London"))
.toOffsetDateTime();
PreparedStatement st = conn.prepareStatement("INSERT INTO mytable (columnfoo) VALUES (?)");
st.setObject(1, odt);
st.executeUpdate();
st.close();

了解现代日期时间API: Trail: Date Time.

最新更新