1

I have the following line in my code:

this.date = new Date(year, month, day);

But when I give, for example:

year = 2008
month = 1
day = 20

I get:

Thu Feb 20 00:00:00 BRT 3908

Or let's say:

year = 2008
month = 3
day = 9

I get:

Thu Apr 09 00:00:00 BRT 3908

Any ideas what's wrong?

3
  • 2
    Nothing is wrong. It does exactly what it's supposed to. Your expectations are wrong. Commented Nov 24, 2013 at 21:49
  • The constructor Date(int year, int month, int date) is deprecated, you should use Calendar.set(year + 1900, month, date) instead. Commented Nov 24, 2013 at 21:54
  • Yeah, I know that, but the teacher said I can only use Date... I don't know why... Anyway, the problem is solved, I'll mark the answer soon. Commented Nov 24, 2013 at 21:58

4 Answers 4

5

You should read the JavaDoc about the constructor. The parameters are not simply what you think they are.

It says:

year - the year minus 1900; must be 0 to 8099. (Note that 8099 is 9999 minus 1900.)
month - 0 to 11
day - 1 to 31

However, as the Docs say as well, it is deprecated. Construct dates using a Calendar instead. Or use JodaTime.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I can't believe that it was that easy. this.date = new Date(year - 1900, month - 1, day);
And about Calendar: Yeah, I know that, but the teacher said I can only use Date... I don't know why...
0

The month is zero-based. So 0 is Jan and 1 is Feb, and so on.

Comments

0

try this

    Date date= new Date();
    SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
    System.out.println(format.format(date));

Comments

0

tl;dr

LocalDate.of( 2008 , Month.JANUARY , 23 )

Legacy classes

As others have said correctly, you assumed month numbers were 1-based counting. But in fact they are 0-based counting. One of the many problems with the java.util.Date/Calendar classes.

As a workaround, use the pre-defined constants rather than try to remember that ridiculous numbering scheme:

java.time

Better yet, get a real date-time framework: Use the JSR 310: Date and Time API classes built into Java 8+.

To represent a date-only value, use LocalDate class. In contrast to the legacy classes, java.time uses sane numbering. For months that is 1-12 for January-December.

LocalDate ld = LocalDate.of( 2008 , 1 , 23 ) ;  // 1 = January.

Or use the nice Month enum.

LocalDate ld = LocalDate.of( 2008 , Month.JANUARY , 23 ) ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.