-1

I am using below code,

private static Date date = new Date (2014-1900,11,25); 
System.out.println(date);

It is displaying 2014-12-25. I am unable to understand why it is giving me date as 12?

and if i give

private static Date date = new Date (2014-1900,12,25); 

it is returning 2015-01-25.

Can anyone help in comprehend this?

MaheshVarma
  • 2,081
  • 7
  • 35
  • 58

4 Answers4

3

Calendar

It accept December month as 11 because month starts from 0 - 11

newuser
  • 8,338
  • 2
  • 25
  • 33
1

First you should not use this Constructor, because it is deprecated.

Second: See the documentation of this consturctor:

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

month is a null based value, so 0 --> Jan ... 11 --> Dec

Jens
  • 67,715
  • 15
  • 98
  • 113
0

from java docs,

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

Month's range from 0-11, ie Jan - Dec

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
-1

Avoid using the depriciated Date() constructor for setting dates, It is recommended to use Calendar class

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2014);
calendar.set(Calendar.MONTH, Calendar.NOVEMBER);
calendar.set(Calendar.DAY_OF_MONTH, 25);
Date date = calendar.getTime();

You can also use the simpleDateFormat for setting/formatting date values:-

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdf.parse("25-11-2014");
Mustafa sabir
  • 4,130
  • 1
  • 19
  • 28
  • using a simpledateformat to initiate a date is just a waste of CPU cycle and possible threading issue – Peter Jan 09 '15 at 07:05
  • But it is better to waste a cpu cycle rather than wasting time setting dates using `new Date (2014-1900,11,25);` and wondering what went wrong. – Mustafa sabir Jan 09 '15 at 07:08
  • I have updated my answer, please check again and see if downvote is really necessary! – Mustafa sabir Jan 13 '15 at 15:10