Bug in Calendar class? it shows 31st feb 2006

H

hemant.singh

please run the following code
Here im creating a GregorianCalendar instance and than add one 27 times
to DAY_OF_MONTH and to my surprise it will show you 31st feb 2006
before moving to march, ,this is really crazy, any1 know of workaround?


public static void main(String[] args)
{
System.out.println("Hello World!");

Calendar calNow = new GregorianCalendar();
String WEEK[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
String MONTH[] = {"January", "Feburary", "March", "April", "May",
"June", "July", "August", "September", "October", "November",
"December"};
String[] options = new String[27];
long values[] = new long [ options.length ];
for (int i = 0; i < options.length; i++ ) {
values = calNow.getTimeInMillis();
options = WEEK[calNow.get(Calendar.DAY_OF_WEEK) - 1]+
", " + calNow.get(Calendar.DAY_OF_MONTH) +
" " + MONTH[ calNow.get(Calendar.MONTH) - 1] +
" " + calNow.get(Calendar.YEAR) ;

calNow.add(Calendar.DAY_OF_MONTH,1);
}
for (int i = 0;i < options.length; i++ )
{
System.out.println(options);
}

}
 
V

VisionSet

please run the following code
Here im creating a GregorianCalendar instance and than add one 27 times
to DAY_OF_MONTH and to my surprise it will show you 31st feb 2006
before moving to march, ,this is really crazy, any1 know of workaround?

setLenient(false)
 
J

Jaakko Kangasharju

please run the following code
Here im creating a GregorianCalendar instance and than add one 27 times
to DAY_OF_MONTH and to my surprise it will show you 31st feb 2006
before moving to march, ,this is really crazy, any1 know of workaround?

Month values in Calendar are 0-based so there is no need to subtract 1
to index into your array. You are actually printing the days for
March, just printing the month as February.
" " + MONTH[ calNow.get(Calendar.MONTH) - 1] +

So remove that -1.
 
V

Vova Reznik

Calendar.JANUARY = 0

Your program prints February instead of March.
You need to change line

MONTH[ calNow.get(Calendar.MONTH) - 1]
to
MONTH[ calNow.get(Calendar.MONTH)]

I know, it is very confusing, because
Calendar.SUNDAY = 1, not 0.
 

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

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top