Resolving MySQL Time Zone Discrepancies in Java Database Connections
In certain scenarios, MySQL database time zones and Java server time zones can result in inconsistencies when working with datetime values. This article addresses this issue and provides a comprehensive solution using the MySQL JDBC connector.
The issue stems from MySQL's default behavior of using the "GMT 8" time zone while Tomcat operates on "GMT". This discrepancy leads to incorrect datetime values being stored in the database and retrieved in Java.
To rectify this, the connection URL must be modified to include the following parameters:
However, this approach has been superseded by a more robust solution involving the use of useLegacyDatetimeCode=false. This parameter disables the legacy datetime handling code and enables the new timestamp handling mechanism in the MySQL JDBC connector.
By setting useLegacyDatetimeCode=false, the Java code can specify a Calendar object while setting timestamps. This Calendar object should be null, as its presence would cause datetime values to be formatted based on the webserver time zone, introducing confusion.
To retrieve datetime values correctly, the getTimestamp(int) method should be used without specifying a Calendar object. This ensures that the database time zone is exclusively used for formatting.
It is important to note that the webserver time zone becomes irrelevant with this approach. Additionally, if MySQL complains about an ambiguous server time zone (e.g., EST), it can be explicitly specified in the connection URL using serverTimezone=
This solution has significantly improved the accuracy of datetime handling when interfacing with MySQL databases from Java applications.
The above is the detailed content of How to Resolve MySQL and Java Time Zone Conflicts in Database Connections?. For more information, please follow other related articles on the PHP Chinese website!