Depending on how you use it, the above code may not be a good idea.
All DateTime constructors that accept int for year / month / day / hour, etc., are vulnerable to Daylight Saving Time (DST) transitions, in which case Joda will throw an exception. So if the hour during the transition is a possible entry into your application, it will not work:
DateTime ny = new DateTime(2011, 3, 13, 2, 0, 0, 0, DateTimeZone.forID("America/New_York")); Exception in thread "main" java.lang.IllegalArgumentException: Illegal instant due to time zone offset transition: 2011-03-13T07:00:00.000 at org.joda.time.chrono.ZonedChronology.localToUTC(ZonedChronology.java:143) at org.joda.time.chrono.ZonedChronology.getDateTimeMillis(ZonedChronology.java:119) at org.joda.time.chrono.AssembledChronology.getDateTimeMillis(AssembledChronology.java:133) at org.joda.time.base.BaseDateTime.<init>(BaseDateTime.java:254) at org.joda.time.base.BaseDateTime.<init>(BaseDateTime.java:223) at org.joda.time.DateTime.<init>(DateTime.java:264)
Similarly, you will encounter another problem in the fall when it is not possible to determine what hour * refers to, since there will be 2 * 2 hours in this time zone. The DateTime withHourOfday and withTime methods are vulnerable to the same problem, as well as to parse datetimes as strings with time zones affected by DST.
Possible workarounds include
- instantiation with any fixed offset time (e.g. UTC)
- UTC timezone parsing
- copying the actual time in the local time zone (for example, at midnight) and using plusHours to move forward to the desired time
- have protection (if-statement) to protect against the second hour of the transition dates.
- catch the exception and check when the next transition will happen (using DateTimeZone.nextTransition), and go back / forward accordingly.
source share