我想知道Java中最简单的方法,以获取将来的日期列表,即日光节省时间将会改变。

做到这一点的一种相当善良的方法是简单地迭代多年的日子,对它们进行测试,以对抗TimeZone.Indaylighttime()。这将起作用,而且我不担心效率,因为这只需要每次我的应用程序启动时运行,但是我想知道是否有一种简单的方法。

如果您想知道我为什么这样做,那是因为我有一个JavaScript应用程序,该应用需要处理包含UTC时间戳的第三方数据。我想要一种可靠的方式,可以从GMT转换为客户端。看 JavaScript- UNIX到特定时区的时间 我已经写了一些可以做到的JavaScript,但是我想从服务器中获得精确的过渡日期。

有帮助吗?

解决方案

乔达时间 (一如既往)由于 DateTimeZone.nextTransition 方法。例如:

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 与它的 nextTransitionpreviousTransition 方法。

其他提示

Java.Time

现代答案使用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归因
不隶属于 StackOverflow
scroll top