Find DST transition timestamp using java.util.TimeZone

Can I get the previous and next DST transition timestamp using the Java Calendar / Date / TimeZone API?
With Joda-Time I can write:

 DateMidnight today = new DateMidnight(2009, 2, 24); DateTimeZone zone = today.getZone(); DateTime previousTransition = new DateTime(zone.previousTransition(today.getMillis())); // 2008-10-26T02:59:59.999+02:00 for Europe/Berlin System.out.println(previousTransition); DateTime nextTransition = new DateTime(zone.nextTransition(today.getMillis())); // 2009-03-29T03:00:00.000+02:00 for Europe/Berlin System.out.println(nextTransition); 

Is there a way to do this with the standard Java APIs?

+4
java jodatime
Feb 24 '09 at 12:32
source share
4 answers

No such functions in java Date / Calendar / TimeZone API

+3
Feb 24 '09 at 12:40
source share

The best thing I've come up with when I need this functionality is to use Calendar and iterations throughout the year, in the specified time zone, and ask, every hour of every day is begging or ending the DST.

You have to do it this way because in the Sun JVM, the TimeZone implementation (sun.util.calendar.ZoneInfo) contains time zone transitions in some kind of β€œcompiled” form.

The code looks something like this:

 public class Dst { Date start; Date end; public static Dst calculate(TimeZone tz, int year) { final Calendar c = Calendar.getInstance(tz); c.setLenient(false); c.set(year, Calendar.JANUARY, 1, 1, 0, 0); c.set(Calendar.MILLISECOND, 0); if (tz.getDSTSavings() == 0) { return null; } Dst dst = new Dst(); boolean flag = false; do { Date date = c.getTime(); boolean daylight = tz.inDaylightTime(date); if (daylight && !flag) { flag = true; dst.start = date; } else if (!daylight && flag) { flag = false; dst.end = date; } c.add(Calendar.HOUR_OF_DAY, 1); } while (c.get(Calendar.YEAR) == year); return dst; } } 

Of course, it makes sense to cache / remember the result of these calculations, etc.

Hope this helps.

+4
Feb 24 '09 at 13:53
source share

Yes, there is an indirect way to get this from the Java API. Check this out and let me know if this works for the problem:

http://monisiqbal.blogspot.com/2009/12/retrieving-time-zones-dst-information.html

This will give you the necessary information for the current year, you can easily do the same in previous years, if you want.

+1
Feb 01 2018-10-0110
source share

With Java 8 you can use

 ZoneRules#nextTransition(Instant) 

&

 ZoneRules#previousTransition(Instant) 

methods to do the same.

https://docs.oracle.com/javase/8/docs/api/java/time/zone/ZoneRules.html

+1
May 05 '17 at 1:16 a.m.
source share



All Articles