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

后端 未结 5 1125
悲&欢浪女
悲&欢浪女 2020-12-24 03:35

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

相关标签:
5条回答
  • 2020-12-24 04:00

    I had the same problem, and it took me nearly a day to track down. I'm storing DateTime columns in MySQL. The RDS instance, running in Amazon's Cloud, is correctly set to have a UTC timestamp by default.

    The Buggy Code is:

        String startTime = "2013-02-01T04:00:00.000Z";
        DateTime dt = ISODateTimeFormat.dateTimeParser().parseDateTime(startTime);            
    
        PreparedStatement stmt = connection.prepareStatement(insertStatementTemplate);
    
        Timestamp ts = new Timestamp(dt.getMillis());
        stmt.setTimestamp(1, ts, Calendar.getInstance(TimeZone.getTimeZone("UTC"))); 
    

    In the code above, the ".setTimestamp" call would NOT take the date as a UTC date!

    After hours of investigating, this turns out to be a known bug in the Java / MySQL Driver. The call to setTimestamp listerally just ignores the Calendar parameter.

    To fix this add the "useLegacyDatetimeCode=false" to your database URI.

    private final static String DatabaseName =
      "jdbc:mysql://foo/?useLegacyDatetimeCode=false";
    

    As soon as i did that, the date stored in the MySQL database was in proper UTC form, rather than in the timezone of my local workstation.

    0 讨论(0)
  • 2020-12-24 04:12

    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! :-)

    0 讨论(0)
  • 2020-12-24 04:14

    A java Date is timezone agnostic. It ALWAYS represents a date in GMD(UTC) in milliseconds from the Epoch.

    The ONLY time that a timezone is relevant is when you are emitting a date as a string or parsing a data string into a date object.

    0 讨论(0)
  • 2020-12-24 04:16

    Well, if we're talking about using PreparedStatements, there's a form of setDate where you can pass in a Calendar set to a particular time zone.

    For instance, if you have a PreparedStatement named stmt, a Date named date, and assuming the date is the second parameter:

    stmt.setDate(2, date, Calendar.getInstance(TimeZone.getTimeZone("GMT")));
    

    The best part is, even if GMT is an invalid time zone name, it still returns the GMT time zone because of the default behavior of getTimeZone.

    0 讨论(0)
  • 2020-12-24 04:18

    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.

    0 讨论(0)
提交回复
热议问题