首页 > 解决方案 > Joda-time:如何将本地时间转换为 UTC,然后仅使用毫秒转换为另一个本地时间?

问题描述

就像 LotR 一样,Java 中的 TimeZone 转换是一个传奇。我的要求很简单。问题在于使用毫秒来创建 DateTime 对象。

我需要能够以毫秒为单位获取本地时间,然后以毫秒为单位将其转换为 UTC,然后将其转换回相同的本地时间,全部使用毫秒。我对 JodaTime 有一些了解,但是在下面的示例中将 UTC 毫秒时间转换回原始本地时间一直是个问题。这是我起床的地方:

public static final TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
public static final String DATETIME_REVERSE = "yyyy-MM-dd 'T' HH:mm:ss";

private void thereAndBackAgain() {

    long nowTimeNumber = 1585715400000L;
    DateTime nowDt = new DateTime(nowTimeNumber);
    DateTimeFormatter formatter = DateTimeFormat.forPattern(DATETIME_REVERSE);
    // Get local time
    Timber.e(" -- 1. Local Time :" + nowDt.getMillis() + " -> " + formatter.print(nowDt));

    // Convert Local to UTC
    DateTime utcTime = nowDt.withZone(DateTimeZone.UTC); // Convert to UTC.
    String utcTimeStr = formatter.print(utcTime);
    long utcOfLocalInMilli = formatter.parseDateTime(utcTimeStr).withZone(DateTimeZone.UTC).getMillis();
    Timber.e(" -- 2. UTC Time   :" + utcOfLocalInMilli + " -> " + formatter.print(utcTime));

    // Convert UTC back to Local
    DateTime utc2 = new DateTime(utcOfLocalInMilli, DateTimeZone.UTC);
    DateTimeFormatter formatter2 = DateTimeFormat.forPattern(DATETIME_REVERSE);
    String utc2str = formatter2.print(utc2);
    long localOfUtcInMillis = formatter2.parseDateTime(utc2str).withZone(DateTimeZone.getDefault()).getMillis();
    Timber.e("  -- 3. Local Time :" + localOfUtcInMillis + " -> " + utc2str);
}

输出是:

 -- 1. Local Time :1585715400000 -> 2020-04-01 T 15:30:00
 -- 2. UTC Time   :1585675800000 -> 2020-04-01 T 04:30:00
 -- 3. Local Time :1585636200000 -> 2020-03-31 T 17:30:00

我遇到的问题是,当我创建 utc2 时,JodaTime 仍然假定毫秒值是本地时区,即使我使用 UTC 时区声明它也是如此。但是我很可能误解了这个构造函数的用法。

基本上,我希望能够从任何时区获取时间,以毫秒为单位转换为 UTC,然后将其转换回任何其他时区。数据库键需要毫秒值。此示例仅使用本地时间,然后转换回相同的时间,但理想情况下,这旨在从一个时区转换为另一个时区,同时使用单个毫秒时间值,然后针对时区进行调整。

标签: jodatimeandroid-jodatime

解决方案


推荐阅读