views:

729

answers:

3

What are the maximum and minimum values of a GregorianCalendar?

Are they in a constant like Integer.MAX_VALUE, or maybe GregorianCalendar.get(BLAH)?

In a nutshell, how can I create a GregorianCalendar instance with min/max value?

+1  A: 

You can try to call Calendar.getMinimum() for each type of field (i.e. year, month, etc.) and then set those minimum values on corresponding field types. This would give you the minimum calendar. I don't know if there is a faster way to do that.

pajton
+2  A: 

This should work:

GregorianCalendar maxgc = new GregorianCalendar();
maxgc.setTime(new Date(Long.MAX_VALUE));

GregorianCalendar mingc = new GregorianCalendar();
mingc.setTime(new Date(Long.MIN_VALUE));
joekutner
Unfortunately your solution doesn't work. After mingc.setTime(new Date(Long.MIN_VALUE)) you get: migc.get(Calendar.YEAR) == 292269055 or sth like this. That doesn't sound like a min to me:-).
pajton
Thank you =DI'm only using these values for comparison so I'm fine, but for others this may be worthy of mention.From setTime() documentation:Note: Calling setTime() with Date(Long.MAX_VALUE) or Date(Long.MIN_VALUE) may yield incorrect field values from get().
WaelJ
pajton, check this:<code>migc.get(Calendar.ERA)</code>0 means BC1 means ADSo year 292269055 corresponds to 292269055 BC
WaelJ
Right. This is quite clever actually;-)
pajton
+2  A: 

I took joekutner's suggestion and ran it with:

GregorianCalendar gCal = new GregorianCalendar( );

gCal.setTime(new Date(Long.MIN_VALUE));
System.out.println( "Min Date is " + gCal.getTime() + " " + gCal.get(Calendar.ERA));

gCal.set( Calendar.SECOND, 3 );
System.out.println( "Min Date less 1 second is " + gCal.getTime() + " " + gCal.get(Calendar.ERA));

gCal.setTime(new Date(Long.MAX_VALUE));
System.out.println( "Max Date is " + gCal.getTime() + " " + gCal.get(Calendar.ERA));


Min Date is Sun Dec 02 16:47:04 GMT 292269055 0
Min Date less 1 second is Sun Aug 17 07:12:54 GMT 292278994 1
Max Date is Sun Aug 17 07:12:55 GMT 292278994 1

Which shows the minimum and maximum, and between them an indication of what happens if you try to move to the second before the minimum - you wrap around.

This was version 1.6.0_17.

martin clayton
Wow that's interesting
WaelJ