1

I'am playing with Java Date and can't understand this:

Date myBirth = new Date(1991,01,21);
Log.d("DATE: ", "" + myBirth);

Here I initialized Date object. Why I get this output?

DEBUG/DATE:(31693): Sat Feb 21 00:00:00 EET 3891
4
  • 2
    January is month 0, February is month 1. Commented Oct 22, 2012 at 22:49
  • 1
    You may wish to avoid writing numeric literals with a leading 0. A leading 0 tells Java to interpret the number as an octal. For numbers less than 8 this makes no difference. However 010 == 8. Commented Oct 22, 2012 at 22:51
  • 1
    this constructor is deprecated. take a look at stackoverflow.com/questions/7661723/… Commented Oct 22, 2012 at 22:59
  • 1
    Opposite stackoverflow.com/questions/13020507/… Commented Oct 22, 2012 at 23:28

3 Answers 3

3

From the Date docs:

  • A year y is represented by the integer y - 1900.
  • A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.
Sign up to request clarification or add additional context in comments.

2 Comments

@AlexKulakovsky, did you read the rest of that document? Specifically the bit that say you pass in the number of years since 1900?
Oops, left the year part out of my original answer, updated now.
2

tl;dr

java.time.LocalDate.of ( 1991 , Month.JANUARY , 21 ) 

Avoid legacy date-time classes

The original date-time classes in Java (Date, Calendar, etc.) are a terribly flawed, bloody awful, horrible mess. Among their many problems: They use insane number for years and months.

Use java.time

Use only the modern java.time classes built into Java 8+ for your date-time work.

The java.time classes use sane numbering. The year 1991 is 1991. Months are 1-12 for January-December.

For January 21, 1991 use the LocalDate class.

LocalDate ld = LocalDate.of ( 1991 , 1 , 21 ) ;

Or use the Month enum.

LocalDate ld = LocalDate.of ( 1991 , Month.JANUARY , 21 ) ;

Comments

1

Quoting from the Javadoc of this deprecated constructor of Date:

Parameters:
    year - the year **minus 1900**.
    month - the month between 0-11.
    date - the day of the month between 1-31.

So the output is what you ask, but not what you want.

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.