600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > mysql中datetime有带时区_当服务器时区不是UTC时 从Java中检索来自MySQL的UTC DATETIME字段...

mysql中datetime有带时区_当服务器时区不是UTC时 从Java中检索来自MySQL的UTC DATETIME字段...

时间:2020-01-10 09:18:02

相关推荐

mysql中datetime有带时区_当服务器时区不是UTC时 从Java中检索来自MySQL的UTC DATETIME字段...

我正在尝试使用Java和MySQL编写代码以与第三方开发的数据库进行互操作 . 此数据库具有一个字段,该字段将 DATETIME 字段中的时间戳存储为UTC日期 . 运行数据库和客户端的服务器的时区设置为非UTC区域( Europe/London ),因此默认情况下,时间戳的读取不正确,就像它是本地时间一样 . 我正在尝试编写代码以将其读回UTC .

我在这里已经阅读了几个类似的问题,但是他们都没有一个对我有用的答案:

不幸的是,我无法更改任何服务器设置,因此我尝试使用连接的"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 | -04-16 10:30:30 |

+----------------+--------+---------------------+

但不幸的是,结果是BST而不是UTC:

java.lang.AssertionError: expected: but was:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。