Datetime behind an hour after insertion. Daylight savings

喜夏-厌秋 提交于 2021-02-17 03:40:06

问题


I've noticed that my MySql database is subtracting an hour from my DateTime objects when I insert certain dates to my tables. Example:

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

I am inserting Java.Sql.Timestamp object (timestamp below) using JdbcTemplate.update:

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;
    }
});

This is only happening for DateTime on/after 28th March 2021 (which is daylight saving time here in the UK). If I insert before 28th March, no time is lost. Example:

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

I have tried using Timestamp rather than DateTime as the MySQL type but it has no effect.

Does anyone know how to stop this behaviour?


回答1:


You can use OffsetDateTime. Since JDBC 4.2 , you can use java.time types directly with JDBC:

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();

Learn about the modern date-time API from Trail: Date Time.




回答2:


Not sure why this was happening, but I fixed the problem by ditching Java.Sql.Timestamp in favour of Java.Time.LocalDateTime.

My insertion code now looks like below (where localDateTime is of type LocalDateTime rather than Timestamp):

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;
    }
});

The MySql database no longer automatically adjusts for timezone.



来源:https://stackoverflow.com/questions/65812572/datetime-behind-an-hour-after-insertion-daylight-savings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!