将 UTC JodaTime.DateTime 对象转换为另一个时区的时间戳

Converting UTC JodaTime.DateTime Object to TimeStamp in another Time Zone

我有一个 Java 应用程序,它使用 MyBatis TypeHandler class。它需要确保存储到 MySql 数据库中的日期是 MST 时间。

在任何数据到达应用程序之前,我们有另一个 TypeHandler 从数据库中获取日期(MST 格式),并将其转换为 UTC。因此,例如,在数据库中,如果时间戳是:

2016-05-05 00:01:00

当日期出现在应用端时,它采用以下格式 (UTC):

2016-05-05T07:01:00.000Z

应用程序端以 UTC 进行所有日期比较,但不幸的是,MySql 服务器必须以 MST 存储。

为了使应用程序 运行ning 中的任何服务器的日期保持一致(在 MST、PST 和 EST 中为 运行)我们将需要两个 TypeHandler,一个用于编组进入应用程序的日期和一个以确保它在 MST 中返回。

UtcToMstDateTimeTypeHanlder 的 setParameter 方法:

@Override
public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException
{
    if (parameter != null)
    {
        //1.  2016-05-05 00:01:00 (timestamp) converted to UTC DateTime -> 2016-05-05T07:01:00.000Z
        DateTime thisDateTime = (DateTime) parameter;
        //2.  UTC DateTime converted to LocalDateTime -> 2016-05-05T07:01:00.000
        LocalDateTime thisLocalDateTime = thisDateTime.toLocalDateTime();
        //3.  LocalDateTime to MST DateTime -> 2016-05-05T07:01:00.000-07:00
        DateTime mstTime = thisLocalDateTime.toDateTime(DateTimeZone.forID("MST"));
        //4.  But TimeStamp adds 3 hours... Why?  2016-05-05 10:01:00.0
        Timestamp mstTimeStamp = new Timestamp((mstTime).getMillis());

        ps.setTimestamp(i, mstTimeStamp);
    }
    else
    {
        ps.setTimestamp(i, null);
    }
}

时间戳最终比 UTC 提前 3 小时:

2016-05-05 10:01:00.0

不仅如此,它与 UTC 的相关性也高于 MST,除了现在比 UTC 早 +10:01 小时。

期望的效果是让 TypeHandler 将日期作为以下时间戳写回数据库:

2016-05-05 00:01:00.0

我只想将提供回数据库的日期(上面的时间戳)与输出的日期相同。

请注意,我现在 运行 在美国东海岸 (EST) 执行此操作。

这是我最终不得不做的事情。请注意下面我正在使用的日期的硬编码,从 UTC 到 MST 类型处理程序。基本思想是获取时区的偏移量。

来自 DateTimeZone JodaTime Class:

getOffset(long instant) Gets the millisecond offset to add to UTC to get local time.

        DateTime thisDateTime = new DateTime("2016-05-07T07:01:00.000Z");

        thisDateTime = thisDateTime.withZone(DateTimeZone.UTC);

        thisDateTime = thisDateTime.toLocalDateTime().toDateTime();

        DateTime mstTime = thisDateTime.withZone(DateTimeZone.forID("MST"));    

        int offset = mstTime.getZone().getOffset(new DateTime().getMillis());

        Timestamp mstTimeStamp = new Timestamp(mstTime.getMillis() + offset); // -25200000 == 7 hours

        ps.setTimestamp(i, mstTimeStamp); //2016-05-07 00:01:00

现在,无论服务器 运行 应用程序代码位于何处,日期始终会正确输入到以 MST 时间运行的数据库中。