Venkat
Venkat

Reputation: 21490

In java, Date() method returns a value. but I am confused in that

I used Date() for getting the date of my birthday, but it was returned the mismatch of the month. My birthday is 04-March-87. so i gave an input as,

Date birthDay = new Date(87,03,04,8,30,00);

But it returns correct year, day and time. But month was problem. It displays April month.

What's wrong with that?

Upvotes: 3

Views: 878

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 338886

tl;dr

LocalDateTime
.of ( 1987 , 3 , 4 , 8 , 30 , 0 )
.atZone( ZoneId.of( "Africa/Tunis" ) )
// 8:30 AM on March 4 of 1987 as seen in the wall-clock/calendar of Tunisia. 

Avoid legacy classes

Among the many flaws in the terrible legacy date-time classes was crazy zero-based counting. So, months were 0-11.

java.time

The legacy classes were supplanted by the modern java.time classes defined in JSR 310.

These classes use sane counting. Months are numbered 1-12 for January-December. Days are 1-7 for Monday-Sunday.

Your code should be revised. Be aware that starting a numeric literal with a zero (0) in Java is an octal number, base 8 — not what you intended.

LocalDateTime ldt = LocalDateTime.of ( 1987 , 3 , 4 , 8 , 30 , 0 );  // 8:30 AM on March 4 of 1987. 
String output = ldt.toString() ;  // 1987-03-04T08:30

By the way, you omitted the time zone or offset. Without that context, we do not know if you meant 8 in the morning in Tokyo Japan, 8 in Toulouse France, or 8 in Toledo Ohio US — three different moments, several hours apart.

If you want to represent a moment, a specific point on the timeline, specify a time zone.

ZoneId z = ZoneId.of( "Asia/Tokyo" );
ZonedDateTime momentOfBirth = ldt.atZone( z ) ;

Upvotes: 3

Buhake Sindi
Buhake Sindi

Reputation: 89169

Months are set from 0 to 11, January =0, February = 1, ..., December = 11.

So, for April do this:

Date birthDate = new Date(87,02,04,8,30,00); //March = 2

Hope this helps;

EDIT

The Date class with this constructor public Date(int year, int month, int date, int hrs, int min) is deprecated (i.e. it has been declared @Deprecated).

Rather do this.

Calendar calendar = Calendar.getInstance();
Calendar.set(1987, 2, 4, 0, 0, 0);
Date birthDate = calendar.getTime();

(It will return the same thing as what you asked for)

Upvotes: 7

Greg Hewgill
Greg Hewgill

Reputation: 993471

The month in the Date class starts with 0 for January, so March is 2, not 3.

Also, the Date(int, int, int, int, int, int) constructor is deprecated, so you should consider using the Calendar class instead.

Finally, be careful with leading zeros in Java - they represent octal constants. The number 09 would not do what you expect.

Upvotes: 5

Related Questions