计算与另一个时区的时差

Calculate hours difference with another timezone

如果我有一个时区,例如“GMT-05:00”
我如何使用 Joda 查找与我当前位置相差多少小时?
我正在使用此代码:

TimeZone tz = TimeZone.getTimeZone("GMT" + gmtTZ);
    
int offset = tz.getOffset((new DateTime().getMillis()));
    
System.out.println(“— > “+offset / 3600000d);
    

给我-5,但它没有考虑我所在时区的时差。

阅读getOffset方法的文档。 Millis from date 不包含任何有关时区的信息,并且 getOffset 采用 millis 参数来判断此特定日期是否在夏令时内。如果是,您将多获得一小时。你这样做的方式永远不会有所不同,你的结果只能是 -5/-4 小时。

你甚至不需要 JodaTime:

TimeZone timezone = TimeZone.getTimeZone("GMT-5");
TimeZone localTimeZone = TimeZone.getDefault();

int timeZoneOffset = timezone.getOffset(System.currentTimeMillis());
int localTimeZoneOffset = localTimeZone.getOffset(System.currentTimeMillis());

int difference = Math.abs(timeZoneOffset - localTimeZoneOffset ) / 3600000;

如果您想要 JodaTime,只需将 System.currentTimeMillis() 替换为 DateTime.now().getMillis(),但我看不到除了可测试性之外的其他要点。