Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a java.util.Date into a MySQL timestamp field in the UTC/GMT timezone?

Tags:

java

mysql

I used a new Date() object to fill a field in a MySQL DB, but the actual value stored in that field is in my local timezone.

How can I configure MySQL to store it in the UTC/GMT timezone?

I think, configuring the connection string will help but I don't know how. There are many properties in the connection string like useTimezone, serverTimzone, useGmtMillisForDatetimes, useLegacyDatetimeCode, ...

like image 688
Behrang Avatar asked Nov 21 '08 15:11

Behrang


2 Answers

The short answer is:

  • add "default-time-zone=utc" to my.cnf
  • in your code, always "think" in UTC, except when displaying dates for your users
  • when getting/setting dates or timestamps with JDBC, always use the Calendar parameter, set to UTC:

    resultset.getTimestamp("my_date", Calendar.getInstance(TimeZone.getTimeZone("UTC")));

  • either synchronize your servers with NTP, or rely only on the database server to tell you what time it is.

The long answer is this:

When dealing with dates and timezones in any database and with any client code, I usually recommend the following policy:

  1. Configure your database to use UTC timezone, instead of using the server's local timezone (unless it is UTC of course).

    • How to do so depends on your database server. Instructions for MySQL can be found here: http://dev.mysql.com/doc/refman/5.0/en/time-zone-support.html. Basically you need to write this in my.cnf: default-time-zone=utc

    • This way you can host your database servers anywhere, change your hosting location easily, and more generally manipulate dates on your servers without any ambiguity.

    • If you really prefer to use a local timezone, I recommend at least turning off Daylight Saving Time, because having ambiguous dates in your database can be a real nightmare.
      • For example, if you are building a telephony service and you are using Daylight Saving Time on your database server then you are asking for trouble: there will be no way to tell whether a customer who called from "2008-10-26 02:30:00" to "2008-10-26 02:35:00" actually called for 5 minutes or for 1 hour and 5 minutes (supposing Daylight Saving occurred on Oct. 26th at 3am)!
  2. Inside your application code, always use UTC dates, except when displaying dates to your users.

    • In Java, when reading from the database, always use:

    Timestamp myDate = resultSet.getTimestamp("my_date", Calendar.getInstance(TimeZone.getTimeZone("UTC")));

    • If you do not do this, the timestamp will be assumed to be in your local TimeZone, instead of UTC.
  3. Synchronize your servers or only rely on the database server's time

    • If you have your Web server on one server (or more) and your database server on some other server, then I strongly recommend you synchronize their clocks with NTP.

    • OR, only rely on one server to tell you what time it is. Usually, the database server is the best one to ask for time. In other words, avoid code such as this:

    preparedStatement = connection.prepareStatement("UPDATE my_table SET my_time = ? WHERE [...]");
    java.util.Date now = new java.util.Date(); // local time! :-(
    preparedStatement.setTimestamp(1, new Timestamp(now.getTime()));
    int result = preparedStatement.execute();

    • Instead, rely on the database server's time:

    preparedStatement = connection.prepareStatement("UPDATE my_table SET my_time = NOW() WHERE [...]");
    int result = preparedStatement.execute();

Hope this helps! :-)

like image 190
MiniQuark Avatar answered Sep 23 '22 06:09

MiniQuark


MiniQuark gave some good answers for databases in general, but there are some MySql specific quirks to consider...

Configure your database to use UTC timezone

That actually won't be enough to fix the problem. If you pass a java.util.Date to MySql as the OP was asking, the MySql driver will change the value to make it look like the same local time in the database's time zone.

Example: Your database if configured to UTC. Your application is EST. You pass a java.util.Date object for 5:00 (EST). The database will convert it to 5:00 UTC and store it. Awesome.

You'd have to adjust the time before you pass the data to "undo" this automatic adjustment. Something like...

long originalTime = originalDate.getTime();
Date newDate = new Date(originalTime - TimeZone.getDefault().getOffset(originalTime));
ps.setDate(1, newDate);

Reading the data back out requires a similar conversion..

long dbTime = rs.getTimestamp(1).getTime();
Date originalDate = new Date(dbTime + TimeZone.getDefault().getOffset(dbTime));

Here's another fun quirk...

In Java, when reading from the database, always use: Timestamp myDate = resultSet.getTimestamp("my_date", Calendar.getInstance(TimeZone.getTimeZone("UTC")));

MySql actually ignores that Calendar parameter. This returns the same value regardless of what calendar you pass it.

like image 28
Ted Bigham Avatar answered Sep 20 '22 06:09

Ted Bigham