Strange behavior of GregorianCalendar

M

Marco Carnazzo

Hi there.

I have this piece of code:

-------
GregorianCalendar date = new GregorianCalendar(23432, 2343244, 9433);
int day = date.get(Calendar.DATE);
int month = date.get(Calendar.MONTH);
int year = date.get(Calendar.YEAR);
System.out.println("Date: " + month + " - " + day + " - " + year);
System.out.println("Time: " + date.getTime());
-------

And the output is:

-------
Date: 1 - 26 - 218728
Time: Sun Feb 26 00:00:00 CET 218728
-------


Strange, uh?
Why isn't there an exception?
How can I validate the GregorianCalendar variable?

Thanks.
 
V

vjg

Hi there.

I have this piece of code:

-------
GregorianCalendar date = new GregorianCalendar(23432, 2343244, 9433);
int day = date.get(Calendar.DATE);
int month = date.get(Calendar.MONTH);
int year = date.get(Calendar.YEAR);
System.out.println("Date: " + month + " - " + day + " - " + year);
System.out.println("Time: " + date.getTime());
-------

And the output is:

-------
Date: 1 - 26 - 218728
Time: Sun Feb 26 00:00:00 CET 218728
-------

Strange, uh?
Why isn't there an exception?
How can I validate the GregorianCalendar variable?

Thanks.
By default, Calendar objects have the "lenient" property set to true.
This causes month and day arguments that are larger than the respective
valid values to be "rolled up". So, setting a date of 2007-13-01 will
be treated as 2008-01-01. If you create your GregorianCalendar object,
use setLenient(false) to turn off this behavior and then set your date
using set(23432, 2343244, 9433) you will get the exception messages you
expected.

- Virgil
 
L

Lew

Marco said:
GregorianCalendar date = new GregorianCalendar(23432, 2343244, 9433);
int day = date.get(Calendar.DATE);
int month = date.get(Calendar.MONTH);
int year = date.get(Calendar.YEAR);
System.out.println("Date: " + month + " - " + day + " - " + year);
System.out.println("Time: " + date.getTime());

n.b., Calendar.JANUARY == 0
<http://java.sun.com/j2se/1.5.0/docs/api/constant-values.html#java.util.Calendar.JANUARY>
<http://java.sun.com/j2se/1.5.0/docs/api/constant-values.html#java.util.Calendar.FEBRUARY>

(My personal favorite Calendar constant is

The result of your constructor was a perfectly valid Calendar object. Strictly
speaking, what you want to validate is the input to the constructor. (Use
vjg's advice.)

- Lew
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,216
Latest member
topweb3twitterchannels

Latest Threads

Top