How do I handle Daylight Savings when working with database through JDBC?

Zhou :

My MySQL server is configured to use UTC (default-time-zone = "00:00" in my.cnf) and I added "serverTimezone=UTC" in the data source URL.

As I understand, this means 2 things:

  1. The MySQL server stores any date/time data in the UTC zone;
  2. The JDBC knows it.

Suppose I have some Dao class with a LocalDateTime field:

class MyDataDao {
    public LocalDateTime theDate = LocalDateTime.parse("2020-01-10T10:00:00");
    // some other fields ...
}

And then I want to insert MyDataDao into the database:

m_jdbc.update(new PreparedStatementCreator() {
    @Override
    public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
        PreparedStatement ps = connection.prepareStatement(SQL_ADDMYDATA, Statement.RETURN_GENERATED_KEYS);
        //... some other fields ...

        // the date time field
        ps.setObject(3, myData.getTheDate());
        return ps;
    }
}, genKey);

Now that here come the questions:

I queried the database in the CLI, it was "2020-01-10 09:00:00".

I am in central Europe, so my "standard" timezone is "UTC+1". It seemed that the JDBC automatically adjusted "theDate" from "UTC+1" to "UTC".

However, I know it is in Daylight Savings Time now, so the practical timezone is actually "UTC+2". Unfortunately, JDBC did not take this into account.

The questions are:

  1. Is all my understanding above correct?
  2. How can I make the JDBC take the DST into account?

(I tried TimeZone.setRawOffset(...) but it did not help. I know I can manually shift the "theDate" field before sending it to the JDBC, but I guess it is definitely not the best practice)

Thank you!

NAIT :

Actually the timezone that will be applied will always depend on the Daylight saving used at the moment refred to by your date and not on the current Dayight saving, it's always easier with an example :

Let's say I created a document in my database with a column creation date containing the value 01/01/2019-12:00:00 UTC.

  • When I query the document the 02/02/2019 (at this time the used time zone offset in paris is UTC+1) then the document returned will have the following value "01/01/2019-13:00:00 Paris".
  • When I query the same document the 01/08/2019 (at this time the used time zone offset in paris is UTC+2) then will also return 01/01/2019-13:00:00 Paris.

So the applied timezone offset depends on your timezone and the daylight saving applied the moment refered to by your date object.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=323951&siteId=1