Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Calendar returns wrong date?

 
Jon Parise
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
 
Jon Parise
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic