我想知道在 Java 中最简单的方法来获取未来夏令时将发生变化的日期列表。
一种相当不优雅的方法是简单地迭代多年的日子,并根据 TimeZone.inDaylightTime() 测试它们。这会起作用,而且我不担心效率,因为这只需要在每次我的应用程序启动时运行,但我想知道是否有更简单的方法。
如果您想知道我为什么这样做,那是因为我有一个 JavaScript 应用程序需要处理包含 UTC 时间戳的第三方数据。我想要一种在客户端从 GMT 转换为 EST 的可靠方法。看Javascript -- Unix 时间到特定时区 https://stackoverflow.com/questions/1044000/javascript-unix-time-to-specific-time-zone我已经编写了一些 javascript 来完成此操作,但我想从服务器获取精确的转换日期。
乔达时间 http://joda-time.sourceforge.net/(一如既往)使这变得非常容易,因为DateTimeZone.nextTransition http://joda-time.sourceforge.net/api-release/org/joda/time/DateTimeZone.html#nextTransition(long)方法。例如:
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;
}
}
}
Output:
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 http://docs.oracle.com/javase/8/docs/api/java/time/zone/ZoneRules.html以其nextTransition
and previousTransition
方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)