Reputation: 495
I am using Joda Time library for parsing the string into dateTime using parseDateTime funtion in this library and noticed that date range supported for this library is -292,269,054 to 292,277,023.
Can anyone know on how to limit date range using this library.Especially with year (YYYY) to 9999?
Thanks.
Upvotes: 5
Views: 622
Reputation: 44061
Joda-Time surprisingly offers what you want (really?). The apparent solution is using LimitChronology. An 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])
My advise is however not to use this feature.
First reason is the inconvenience to apply the LimitChronology
on every DateTime
-object in your program. Probably you would be forced to change your application architecture to install a central factory for producing such exotic DateTime
-objects in order to be sure that you really don't forget any object.
Another reason is the partial unreliability of the chronology in question. It can not prevent instantiating DateTime
-objects outside of the supported limited range but produces strange formatted output (see example above).
Therefore I suggest you to follow the advise of @MadProgrammer or @CharlieS using Interval
for range checks.
Upvotes: 1
Reputation: 5655
I am not sure, but you can test with this code
DateTime startRange = new DateTime(2010, 1, 1, 12, 0, 0, 0);
DateTime endRange = new DateTime(9999, 12, 31, 21, 59, 59, 59);
Interval interval = new Interval(startRange, endRange);
DateTime testRange = new DateTime(2014, 10, 30, 11, 0, 0, 0);
System.out.println(interval.contains(testRange)); // returns true
endRange = new DateTime(2014, 12, 31, 21, 59, 59, 59);
testRange = new DateTime(9999, 10, 30, 11, 0, 0, 0);
System.out.println(interval.contains(testRange)); // returns false
Upvotes: 0
Reputation: 338326
As MadProgrammer commented, limiting a date range is your job as the app developer. Joda-Time cannot know what you consider to be reasonable limits.
To help with that chore of validating data, you might find the Bean Validation spec useful. Defined by JSR 303 (spec 1.0) and JSR 349 (spec 1.1).
With Bean Validation, you can conveniently use annotations to define rules such as a minimum and maximum value for a particular member variable in a class.
Upvotes: 1