JChris
JChris

Reputation: 1678

Wrong (Date) date return in Java

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?

Upvotes: 1

Views: 150

Answers (4)

Basil Bourque
Basil Bourque

Reputation: 338516

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 ) ;

Upvotes: 0

subash
subash

Reputation: 3140

try this

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

Upvotes: 0

peter.petrov
peter.petrov

Reputation: 39457

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

Upvotes: 0

Martijn Courteaux
Martijn Courteaux

Reputation: 68847

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.

Upvotes: 5

Related Questions