Joda-Time unexpectedly offers what you want (really?). The obvious solution is using LimitChronology . Example:
DateTime min = new DateTime(2014, 1, 1, 0, 0); DateTime max = new DateTime(2015, 1, 1, 0, 0).minusMillis(1); Chronology chronology = LimitChronology.getInstance(ISOChronology.getInstance(), min, max); DateTime now = DateTime.now(chronology); System.out.println(now.toString(DateTimeFormat.fullDateTime())); // output: Donnerstag, 6. November 2014 19:08 Uhr MEZ DateTime test = new DateTime(1970, 1, 1, 0, 0).withChronology(chronology); System.out.println(test.toString(DateTimeFormat.fullDateTime())); // no exception! => output: , . : Uhr MEZ test = now.withYear(1970); // IllegalArgumentException: // The resulting instant is below the supported minimum of // 2014-01-01T00:00:00.000+01:00 (ISOChronology[Europe/Berlin])
However, my advice should not use this feature.
The first reason is the inconvenience of using LimitChronology for each DateTime object in your program. You will probably have to change the architecture of the application to set up a central factory to create such exotic DateTime objects to make sure that you really haven't forgotten any object.
Another reason is the partial unreliability of the chronology in question. It cannot prevent the creation of instances of DateTime objects outside the supported limited range, but it creates strange formatted output (see the Example above).
Therefore, I suggest that you follow the recommendations of @MadProgrammer or @CharlieS, using Interval to check the range.
source share