【问题标题】:jodatime how to know if daylight savings is onjodatime 如何知道夏令时是否开启
【发布时间】:2023-03-18 21:37:01
【问题描述】:

我有一个需要时区的 API。例如。如果我在加利福尼亚州,我需要在夏令时开启时将 -7 传递给它(加利福尼亚州,PDT 是 GMT - 7),在夏令时关闭时将 -8 传递给它。但我无法弄清楚当前日期是开启还是关闭夏令时。

Date date1 = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
double[] coords = db.getCoords(id1);
double latitude = coords[0];
double longitude = coords[1];
double timezone = -7; /* For Pacific daylight time (GMT - 7)*/

ArrayList<String> Times = Class.foo(cal, latitude,
longitude, timezone);

我已经安装了 JodaTime,即使在那里我也找不到方法。请建议本地 java 或 jodatime 是否有这样做的方法。

【问题讨论】:

标签: android timezone jodatime dst


【解决方案1】:

当您使用 JodaTime 创建DateTime 时,您不需要传递偏移量。相反,通过时区。它将负责确定正确的偏移量,包括考虑 DST。

// First get a DateTimeZone using the zone name
DateTimeZone zone = DateTimeZone.forID("America/Los_Angeles");

// Then get the current time in that zone.
DateTime dt = new DateTime(zone);

// Or if you prefer to be more explicit, this syntax is equivalent.
DateTime dt = DateTime.now(zone);

更新

我仍然不确定您到底在问什么,但也许您正在寻找以下其中之一:

// To get the current Pacific Time offset
DateTimeZone zone = DateTimeZone.forID("America/Los_Angeles");
int currentOffsetMilliseconds = zone.getOffset(Instant.now());
int currentOffsetHours = currentOffsetMilliseconds / (60 * 60 * 1000);


// To just determine if it is currently DST in Pacific Time or not.
DateTimeZone zone = DateTimeZone.forID("America/Los_Angeles");
boolean isStandardOffset = zone.isStandardOffset(Instant.now());
boolean isDaylightOffset = !isStandardOffset;

【讨论】:

  • 马特,如果夏令时开启,我想知道“给定时间或日期”。基本上我正在寻找的关键是我上面代码中参数“双时区”的值。我有一个日期被传递给它。使用日期和位置我想知道夏令时是打开还是关闭。例如。 2013 年 11 月之后,我的时区值应该是 -8
  • 嗯,您首先需要从该位置解析时区。乔达时间不能为你做到这一点。您需要使用其中一种方法described here。
  • 我认为您没有收到我的问题。我的位置是加利福尼亚,它是静态的。我必须调用一个 api“int Foo(double x)”。变量 x 应该是 (GMT -7) 或 (GMT -8) 基于日期,即取决于夏令时是打开还是关闭。我想知道日期是否是夏令时。如果它打开,我应该将 -7 传递给 api。我不明白您的任何答案如何解决我的问题。
  • 请阅读timezone tag wiki 中的“TimeZone != Offset”。如果您只有一个偏移量,那么您无法确定该偏移量是否在 DST 中。您需要一个时区。由于您有坐标,因此您可以从中确定时区。如果您的位置始终在加利福尼亚,那么您的时区始终是America/Los_Angeles,无需查找。也无需告诉 Joda 在该区域中 DST 是打开还是关闭。如果我仍然以某种方式错过了您的问题的意图,请澄清。
  • 马特,感谢您的更新。您的第二次更新回答了我的问题。唯一的问题是我有一个特定的日期,我想知道 DST 是否开启。因此,根据您的第二个代码示例 // 确定它是否在太平洋时间的 Date "mm-dd-yy" DST 上。 DateTimeZone zone = DateTimeZone.forID("America/Los_Angeles"); //假设 date1 = "11-13-2013" boolean isStandardOffset = zone.isStandardOffset(date1); boolean isDaylightOfset = !isStandardOffset;
猜你喜欢
  • 2014-10-27
  • 2018-12-12
  • 2012-07-08
  • 2021-06-22
  • 2012-11-25
  • 2014-10-06
  • 1970-01-01
  • 2011-05-12
  • 2018-12-23
相关资源
最近更新 更多