java - 在 Java 中获取时区的夏令时转换日期

标签 java date dst

我想知道在 Java 中获取夏令时将发生变化的 future 日期列表的最简单方法。

执行此操作的一种相当不雅的方法是简单地迭代多年的天数,根据 TimeZone.inDaylightTime() 测试它们。这会起作用,而且我不担心效率,因为它只需要在我的应用程序每次启动时运行,但我想知道是否有更简单的方法。

如果您想知道我为什么这样做,那是因为我有一个 javascript 应用程序需要处理包含 UTC 时间戳的第三方数据。我想要一种在客户端从 GMT 转换为 EST 的可靠方法。参见 Javascript -- Unix Time to Specific Time Zone我已经编写了一些可以执行此操作的 javascript,但我想从服务器获取准确的转换日期。

最佳答案

Joda Time (一如既往)由于 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 - 在 Java 中获取时区的夏令时转换日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1449500/

相关文章:

c# - 将 MVC 默认日期 (01/01/0001) 格式化为空

date - Grails:在新的Date()中迭代一天

java - Java 中的夏令时调整

sql - 夏令时和 UTC 时间

java - Java中如何轻松顺利地从MediaType.JSON的数据中获取数据?

java - for循环内的变量声明

iOS - 友好的 NSDate 格式

java - 如何计算考虑到日节省类次的日期之间的天数?

java - 为 netbeans 8.2 运行 SQL 时出现词法错误

java - 使用本地端口从网站发送 TCP/IP 请求