wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Calendar returns wrong date? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Calendar returns wrong date?" Watch "Calendar returns wrong date?" New topic
Author

Calendar returns wrong date?

Jon Parise
Ranch Hand

Joined: Jul 03, 2007
Posts: 81
Hey everyone,

Either I have a bug or Sun is playing an April Fools joke on me. Is there any possible way that Calendar.getInstance() would return a date of 3/1/2008 instead of 4/1/2008??

Maybe one of you can find the error in my code. I am tryign to set 4 text boxes. One set had today's date and time the other has yesterday's date and time. Strangely I am getting the wrong date...



The output of c.toString() is:


java.util.GregorianCalendar[time=1207053201873,areFieldsSet=true,
areAllFieldsSet=true,lenient=true,
zone=sun.util.calendar.ZoneInfo[id="America/New_York",
offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,
lastRule=java.util.SimpleTimeZone[id=America/New_York,offset=-18000000,
dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,
startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,
endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,
endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2008,
MONTH=3,WEEK_OF_YEAR=14,WEEK_OF_MONTH=1,DAY_OF_MONTH=1,DAY_OF_YEAR=92,
DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=8,HOUR_OF_DAY=8,MINUTE=33,
SECOND=21,MILLISECOND=873,ZONE_OFFSET=-18000000,DST_OFFSET=3600000]



It is particularly troubling that Month = 3 instead of 4. Any ideas?

[edited to get better formatting in post]
[ April 01, 2008: Message edited by: Fred Rosenberger ]
Marco Ehrentreich
best scout
Bartender

Joined: Mar 07, 2007
Posts: 1280

Hi Jon,

the output is correct from the perspective of Calendar. Unfortunately the API of the Calendar class was designed to start counting of months with zero! Probably nobody knows why but it's a fact.

So for your problem: getMonth() == 3 represents April! Just don't think about the "why"

Marco
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3456
    
  12
Months in teh Calendar class are numbered from 0 to 11, so you need to add one to the value returned by c.get(Calendar.MONTH)


Joanne
Jon Parise
Ranch Hand

Joined: Jul 03, 2007
Posts: 81
Typical programmers counting from 0....

I thought 1 of 3 scenarios were possible.

1) I missed something
2) I found a horrific bug in the calendar class
3) Sun was having April Fool's fun when they released the latest version of J2SE...

Thanks for the help!
 
 
subject: Calendar returns wrong date?