This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is java Date/Calendar a bug?

 
Li Shangqiang
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I used java.util.Calendar like this:
Calendar calendar = new GregorianCalendar(2001, 6, 30);
calendar.add(Calendar.DATE, 1);
//or calendar.add(Calendar.DATE, 1);
//or calendar.add(Calendar.HOUR, 24);
System.out.println("year: "+calendar.get(Calendar.YEAR)+
"\n month: "+calendar.get(Calendar.MONTH)+
"\n day: "+calendar.get(Calendar.DAY_OF_MONTH)+
"\n hour: "+calendar.get(Calendar.HOUR)+
"\n minute: "+calendar.get(Calendar.MINUTE)+
"\n sencond: "+calendar.get(Calendar.SECOND)
);
the result is always 2001-6-31!
then i use java.util.Date:
Date date = new Date(2001, 6, 30);
long current = date.getTime();
current += 24 * 3600 * 1000; //add one day
System.out.println(..
and the result is the same!
who answer me?
 
rani bedi
Ranch Hand
Posts: 358
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no problem with the java.util.date object.
If you try to convert the time back into the date object you would see that it prints the next date.

Date date = new Date(2001, 6, 30);
long current = date.getTime();
current += 24 * 3600 * 1000; //add one day
Date newDate = new Date(current);
System.out.println(" date " + date);
System.out.println(" newDate " + newDate);
 
Paul Stevens
Ranch Hand
Posts: 2823
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are referring to 6-31 and thinking it is June 31 you are mistaken. Java months start at 0 for Jan. So 6-31 is Jul 31.
 
Li Shangqiang
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that's the problem.
I'v got it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic