MySQL - how to store time with correct timezone? (from Java)

后端 未结 3 441
清歌不尽
清歌不尽 2020-12-11 10:50

I\'m using MySQL 5.0. I need to store date-time information in one column. I mean to use DATETIME or TIMESTAMP column type. But I have problem with

相关标签:
3条回答
  • 2020-12-11 11:32

    Your best bet, in my view, is to tell MySQL to use GMT and handle all local time issues in your application code, not your database. The values in the database would always be GMT, full stop, which is unambiguous. As you say, with daylight savings time (summer time) adjustments, you can end up with the same value in your database for what is, to us humans, two different times.

    This also makes the database portable. If you move to North America and start using MySQL set to (say) Central time, all of a sudden the values in your database seem to have moved several hours. I had that issue with a database I inherited which was using the server's local time, when I moved it from the east coast of the U.S. to the west coast, not having thought to check whether MySQL was slaved to the machine's zone...

    0 讨论(0)
  • 2020-12-11 11:34

    DATE, TIME, YEAR and DATETIME all store the respective date/time indications, just like taking a photograph of a calendar and/or clockface: they do not record the timezone in which the clock was set, so they don't represent any particular moment in time. They're useful for events that occur on a specific local date or at a specific local time (i.e. irrespective of timezone).

    TIMESTAMP stores a UTC timestamp (as seconds since the UNIX epoch), performing conversion to/from your session's time_zone as necessary: it represents a precise, unambiguous moment in time. This is what you want; just be sure to set your session variable as appropriate (with SET SESSION time_zone = ...).

    See MySQL Server Time Zone Support for more information.

    0 讨论(0)
  • 2020-12-11 11:39

    You could convert the date to UTC before storing in the database, then convert back to your own time zone when reading from the database.

    long t = 1351382400000; // the timestamp in UTC
    String insert = "INSERT INTO my_table (timestamp) VALUES (?)";
    PreparedStatement stmt = db.prepareStatement(insert);
    java.sql.Timestamp date = new Timestamp(t);
    stmt.setTimestamp(1, date);
    stmt.executeUpdate();
    
    .....
    
    TimeZone timezone = TimeZone.getTimeZone("MyTimeZoneId");
    Calendar cal = java.util.Calendar.getInstance(timezone);
    String select = "SELECT timestamp FROM my_table";
    // some code omitted....
    ResultSet rs = stmt.executeQuery();
    while (rs.next()) {
       java.sql.Timestamp ts = rs.getTimestamp(1);
       cal.setTimeInMillis(ts.getTime());
       System.out.println("date in db: " + cal.getTime());
    }
    
    0 讨论(0)
提交回复
热议问题