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

后端 未结 5 1147
悲&欢浪女
悲&欢浪女 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: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.

提交回复
热议问题