当服务器时区不是 UTC 时,从 Java 中的 MySQL 检索 UTC 日期时间字段

2022-09-01 19:32:11

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

我在这里读过几个类似的问题,但没有一个答案适合我:

不幸的是,我无法更改任何服务器设置,因此我尝试使用连接的“time_zone”变量将数据库服务器设置为使用UTC和可选参数来检索日期,但这对结果没有影响。这是我的代码:CalendarResultSet.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>

答案 1

您的客户端代码看起来是正确的。我认为您还需要获取MySQL Connector / J JDBC驱动程序,以将表中存储的日期视为UTC日期,以避免虚假的时区转换。这意味着除了用于 JDBC 调用的客户端会话时区和日历之外,还要设置有效的服务器时区。getDate()getTimestamp

查看您在失败的断言中获得的值,以及错误位于哪个方向:

expected:<Thu Apr 16 11:30:30 BST 2015> but was:<Thu Apr 16 10:30:30 BST 2015>

你回来的是英国夏令时10:30,也就是格林尼治标准时间9:30。这与数据库将表中的 10:30 视为 BST 值,并在将其解析为 GMT 日期之前,将其虚假地转换为 GMT 是一致的。这与将GMT值虚假转换为BST的方向相反。

这可能是一个特定于 JDBC 的问题,因为 JDBC 要求将时间转换为本地区域。(MySQL C API没有,可能是因为C的经典时间类型不像Java那样具有区域感知能力。它还需要知道它哪个区域转换过来。MySQL类型始终存储为UTC。但对于类型,这并没有说明。我认为这意味着MySQL将把列值解释为在服务器的时区中。您提到的设置为BST,这与断言错误消息中显示的转移方向一致。TIMESTAMPDATETIMEDATETIME

您设置的会话变量告诉MySQL服务器客户端计算机的时区是什么,但它不会影响服务器认为自己的时区是什么。这可以用 serverTimezone JDBC 连接属性覆盖。在连接上,将 设置为 UTC,并确保处于关闭状态。(如果不起作用,请查看其他与区域相关的属性。查看这是否使您的日期以 UTC 形式出现,并具有与数据库中相同的日历字段值。time_zoneserverTimezoneuseLegacyDatetimeCode

请注意,这将改变对数据库中其他值的解释:它们现在看起来都像 UTC 日期(在 JDBC 连接的上下文中)。这是否正确将取决于它们最初是如何填充的。虽然您的客户端代码将具有您想要的行为,但我不知道是否可以使整个系统的行为完全一致,而无需在服务器级别将服务器的时区设置为UTC。基本上,如果它没有将其区域设置为UTC,则它未针对您想要的行为进行完全配置,并且您正在围绕它进行笨拙。DATETIME


答案 2

也许你可以使用JodaTime,如下所示;

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=?"))
    {
        s.setLong (1, getPhysId ());
        try (ResultSet rs = s.executeQuery ())
        {
            if (!rs.next ()) return null;
            DateTime dt = new LocalDateTime(rs.getTimestamp(1,UTCCALENDAR).getTime ()).toDateTime(DateTimeZone.forID("Europe/London"));  

            return dt.toDate();               }
    }
    catch (SQLException e)
    {
        throw new MailAccessException ("Error accessing dbmail database", e);
    }
}

编辑:

java.util.Date 不是时区不可知的。toDateTime的方法负责时区和DST,所以你不关心它

下面的代码:

public static void main(String[] args) {
    // 29/March/2015 1:05 UTC
    DateTime now = new DateTime(2015, 3,29,1,5,DateTimeZone.UTC);
    // Pre DST 29/March/2015 0:30 UTC
    DateTime preDst = new DateTime(2015, 3,29,0,30,DateTimeZone.UTC);
    System.out.println("1:05 UTC:"+now);
    System.out.println("0:30 UTC:"+preDst);
    DateTimeZone europeDTZ = DateTimeZone.forID("Europe/London");
    DateTime europeLondon = now.toDateTime(europeDTZ);
    System.out.println("1:05 UTC as Europe/London:"+europeLondon);
    DateTime europeLondonPreDst = preDst.toDateTime(europeDTZ);
    System.out.println("0:30 UTC as Europe/London:"+europeLondonPreDst);
}

将打印:

1:05 UTC:2015-03-29T01:05:00.000Z
0:30 UTC:2015-03-29T00:30:00.000Z
1:05 UTC as Europe/London:2015-03-29T02:05:00.000+01:00
0:30 UTC as Europe/London:2015-03-29T00:30:00.000Z

如果你能看到JodaTime负责DST。