当服务器时区不是 UTC 时,从 Java 中的 MySQL 检索 UTC 日期时间字段
我正在尝试编写代码,以使用Java和MySQL与第三方开发的数据库进行互操作。此数据库有一个字段,该字段将字段中的时间戳存储为 UTC 日期。运行数据库和客户端的服务器的时区设置为非 UTC 区域 (),因此默认情况下,时间戳被错误地读回,就好像它是本地时间一样。我正在尝试编写代码以将其读回为UTC。DATETIME
Europe/London
我在这里读过几个类似的问题,但没有一个答案适合我:
- MySQL - 如何使用正确的时区存储时间?(来自爪哇)
- 如何将java.util.Date存储在UTC / GMT时区的MySQL时间戳字段中?
- 以 UTC 格式的日期(以 mysql 为单位)
- 如何设置 MySQL 的时区?
不幸的是,我无法更改任何服务器设置,因此我尝试使用连接的“time_zone”变量将数据库服务器设置为使用UTC和可选参数来检索日期,但这对结果没有影响。这是我的代码:Calendar
ResultSet.getTimestamp
private static final Calendar UTCCALENDAR = Calendar.getInstance (TimeZone.getTimeZone (ZoneOffset.UTC));
public Date getDate ()
{
try (Connection c = dataSource.getConnection ();
PreparedStatement s = c
.prepareStatement ("select datefield from dbmail_datefield where physmessage_id=?"))
{
fixTimeZone (c);
s.setLong (1, getPhysId ());
try (ResultSet rs = s.executeQuery ())
{
if (!rs.next ()) return null;
return new Date (rs.getTimestamp(1,UTCCALENDAR).getTime ()); // do not use SQL timestamp object, as it fucks up comparisons!
}
}
catch (SQLException e)
{
throw new MailAccessException ("Error accessing dbmail database", e);
}
}
private void fixTimeZone (Connection c)
{
try (Statement s = c.createStatement ())
{
s.executeUpdate ("set time_zone='+00:00'");
}
catch (SQLException e)
{
throw new MailAccessException ("Unable to set SQL connection time zone to UTC", e);
}
}
我尝试读取的数据库字段存储了一个值,如下所示:
mysql> select * from dbmail_datefield where physmessage_id=494539;
+----------------+--------+---------------------+
| physmessage_id | id | datefield |
+----------------+--------+---------------------+
| 494539 | 494520 | 2015-04-16 10:30:30 |
+----------------+--------+---------------------+
但不幸的是,结果是BST而不是UTC:
java.lang.AssertionError: expected:<Thu Apr 16 11:30:30 BST 2015> but was:<Thu Apr 16 10:30:30 BST 2015>