[英]Get Daylight Saving Transition Dates For Time Zones in Java
我想知道在 Java 中使用最簡單的方法來獲取未來夏令時將發生變化的日期列表。
一種相當不優雅的方法是簡單地迭代幾年的天數,根據 TimeZone.inDaylightTime() 測試它們。 這會奏效,而且我不擔心效率,因為它只需要在我的應用程序每次啟動時運行,但我想知道是否有更簡單的方法。
如果您想知道我為什么要這樣做,那是因為我有一個 javascript 應用程序需要處理包含 UTC 時間戳的第三方數據。 我想要一種在客戶端從 GMT 轉換為 EST 的可靠方法。 請參閱Javascript -- Unix 時間到特定時區我已經編寫了一些 javascript 可以做到這一點,但我想從服務器獲取精確的轉換日期。
由於DateTimeZone.nextTransition
方法, Joda Time (一如既往)使這變得非常容易。 例如:
import org.joda.time.*;
import org.joda.time.format.*;
public class Test
{
public static void main(String[] args)
{
DateTimeZone zone = DateTimeZone.forID("Europe/London");
DateTimeFormatter format = DateTimeFormat.mediumDateTime();
long current = System.currentTimeMillis();
for (int i=0; i < 100; i++)
{
long next = zone.nextTransition(current);
if (current == next)
{
break;
}
System.out.println (format.print(next) + " Into DST? "
+ !zone.isStandardOffset(next));
current = next;
}
}
}
輸出:
25-Oct-2009 01:00:00 Into DST? false 28-Mar-2010 02:00:00 Into DST? true 31-Oct-2010 01:00:00 Into DST? false 27-Mar-2011 02:00:00 Into DST? true 30-Oct-2011 01:00:00 Into DST? false 25-Mar-2012 02:00:00 Into DST? true 28-Oct-2012 01:00:00 Into DST? false 31-Mar-2013 02:00:00 Into DST? true 27-Oct-2013 01:00:00 Into DST? false 30-Mar-2014 02:00:00 Into DST? true 26-Oct-2014 01:00:00 Into DST? false 29-Mar-2015 02:00:00 Into DST? true 25-Oct-2015 01:00:00 Into DST? false ...
在 Java 8 中,您可以使用ZoneRules
及其nextTransition
和previousTransition
方法獲取相同的信息。
現代答案使用 java.time,現代 Java 日期和時間 API。
ZoneId zone = ZoneId.of("Europe/London");
ZoneRules rules = zone.getRules();
ZonedDateTime now = ZonedDateTime.now(zone);
ZoneOffsetTransition transition = rules.nextTransition(now.toInstant());
Instant max = now.plusYears(15).toInstant();
while (transition != null && transition.getInstant().isBefore(max)) {
System.out.println(transition);
transition = rules.nextTransition(transition.getInstant());
}
輸出,縮寫:
Transition[Overlap at 2019-10-27T02:00+01:00 to Z] Transition[Gap at 2020-03-29T01:00Z to +01:00] Transition[Overlap at 2020-10-25T02:00+01:00 to Z] Transition[Gap at 2021-03-28T01:00Z to +01:00] Transition[Overlap at 2021-10-31T02:00+01:00 to Z] Transition[Gap at 2022-03-27T01:00Z to +01:00] Transition[Overlap at 2022-10-30T02:00+01:00 to Z] (cut) Transition[Overlap at 2033-10-30T02:00+01:00 to Z] Transition[Gap at 2034-03-26T01:00Z to +01:00]
不過,我不會太相信數據。 我不確定英國退歐后(以及歐盟可能在 2021 年放棄夏令時 (DST) 之后)在英國的時間會發生什么變化。
鏈接: Oracle 教程:解釋如何使用 java.time 的日期時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.