File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Calendar returns wrong date?" Watch "Calendar returns wrong date?" New topic

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:


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

Joined: Mar 07, 2007
Posts: 1294

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"

Joanne Neal

Joined: Aug 05, 2005
Posts: 3742
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

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!
I agree. Here's the link:
subject: Calendar returns wrong date?
It's not a secret anymore!