【问题标题】:Joda time gives incorrect time for timezoneJoda time 给出的时区时间不正确
【发布时间】:2015-10-19 03:49:08
【问题描述】:

我正在 Android 中创建一个微调器,然后获取微调器的值并尝试在时区 ID 中找出本地时间。

在以下示例中,timeZoneID 是时区 ID 的字符串表示形式,例如“美国/芝加哥”等

            DateTimeZone tz = DateTimeZone.forID(timeZoneID);
            DateTime now = DateTime.now(DateTimeZone.forID(timeZoneID));
            DateTime localTime1 = now.toDateTime(tz);

            float minuteRotation = localTime1.getMinuteOfDay() / 30f * (float) Math.PI;
            float hourRotation = ((localTime1.getHourOfDay() + localTime1.getMinuteOfDay() / 60f) / 6f) * (float) Math.PI;

然而,问题是时区的本地时间总是错误的。例如,如果 PST 时间应该是晚上 8 点,那么我从上面的代码中返回下午 5 点。

所有时区 ID 都是正确的,并且是从 Joda 时间本身获得的,这些时间本身填充在以下微调器中:

        Set<String> zoneIds = DateTimeZone.getAvailableIDs();
        DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("ZZ");
        ArrayList<String> TZ1 = new ArrayList<String>();
        for(String zoneId:zoneIds) {
            TZ1.add("("+dateTimeFormatter.withZone(DateTimeZone.forID(zoneId)).print(0) +") "+zoneId+", "+TimeZone.getTimeZone(zoneId).getDisplayName());
        }

        for(int i = 0; i < TZ1.size(); i++) {
            adapter.add(TZ1.get(i));
        }
        final Spinner TZone = (Spinner)findViewById(R.id.TimeZoneEntry);
        TZone.setAdapter(adapter);
        for(int i = 0; i < TZ1.size(); i++) {
            if(TZ1.get(i).equals(TimeZone.getDefault().getDisplayName())) {
                TZone.setSelection(i);
            }
        }

问题:为什么我从 Joda 时间得到的当地时间不正确?我正在努力解决这个问题!

【问题讨论】:

  • 设备本地时间是否设置为其他时区?这可能会导致偏移。你可以查看这个帖子:stackoverflow.com/questions/4312680/…
  • 当地时间也设置为 PST - 所以从技术上选择美国/洛杉矶也应该与当地时间相同。
  • 您是否 100% 确定地验证了 timeZoneID 的值是您认为的值?为什么在将区域加载到微调器时要在区域周围添加括号?

标签: java android time jodatime wear-os


【解决方案1】:

以下代码作为测试报告了我的时区设置的正确本地时间:

@Test
public void timeTest()
{
    String timeZoneID = "Europe/Berlin";
    DateTimeZone tz = DateTimeZone.forID(timeZoneID);
    DateTime now = DateTime.now(DateTimeZone.forID(timeZoneID));
    DateTime localTime1 = now.toDateTime(tz);
    System.err.println(localTime1 + " " + localTime1.getZone().getID() + " Default: " + TimeZone.getDefault().getID());
}

当前设置不应该是PDT 而不是PST?而且“美国/芝加哥”比太平洋夏令时间晚 3 小时。

【讨论】:

  • 那与我的代码完全相同。这真的很奇怪,它对你有用,而不是对我有用。
  • 我的输出是2015-07-28T20:43:41.956+02:00 Europe/Berlin Default: Europe/Berlin。您可以在其他设备上尝试吗?我这里没有安卓设备可以测试。
猜你喜欢
  • 1970-01-01
  • 2012-07-22
  • 2011-07-06
  • 1970-01-01
  • 2018-05-18
  • 1970-01-01
  • 2013-09-03
  • 1970-01-01
  • 2020-08-22
相关资源
最近更新 更多