• Post Reply Bookmark Topic Watch Topic
  • New Topic

Date not working  RSS feed

 
Ind Sans
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Following is the code for adding date

public boolean addDate(int iDate)
{

Calendar cal = Calendar.getInstance();

cal.set(2009,02,01);
cal.add(Calendar.DATE, iDate); // Add days in Dates in Calendar


System.out.println("Date :"+cal.get(Calendar.DATE));
System.out.println("Month :"+cal.get(Calendar.MONTH));
System.out.println("Year :"+cal.get(Calendar.YEAR));

return true;
}

calling the function.
addDate(30);

But the output is giving wrongly, previously for couple of months it was working fine, but now I don't understand why the date function is throwing wrong error
Date :31
Month :2
Year :2009


I don't understand what to do!
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch. Please UseCodeTags when you post source code.

The problem is in this line:

Months in class Calendar are (unfortunately) zero-based, So month 02 is actually March, not February. It's better to use the constants defined in class Calendar than to use numbers:


Note that when you do cal.get(Calendar.MONTH); you will also get a zero-based month number, so 2 is actually March, not February.

Another problem is that when you write numbers starting with a zero, such as "01" and "02" in your code, those numbers will be interpreted as octal numbers - not decimal numbers. If you'd write "08", you would get a compiler error, because 8 is not a valid digit in the octal number system.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!