Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calendar .YEAR, .MONTH, DAY_OF_MONTH different than date.getDay() etc?

I realized this:

Calendar c = new GregorianCalendar();
mYear=c.get(Calendar.YEAR);
mMonth=c.get(Calendar.MONTH);
mDay=c.get(Calendar.DAY_OF_MONTH);

And this:

Date d = c.getTime();
int day = d.getDay();
int month = d.getMonth();
int year= d.getYear();

Yield different numbers, is there some initialization I am missing? I care because I am using ORMLite and trying to store dates into a database, which is a Date object, but Date is being deprecated and so I am trying now to use Calendar but it doesn't seem that simple since the above code results in different answers for the day, month, and year.

like image 364
Codejoy Avatar asked Jul 28 '11 15:07

Codejoy


1 Answers

the Date.getYear(), getMonth() and getDay() are deprecated and specifically ask you to use Calendar.get()

The reason why you are getting different answers is two-fold

getDay() returns the day of the week and not the date -- use getDate() here

getYear() returns year - 1900

Here is the relevant note from the API documentation

Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR) - 1900.

http://download.oracle.com/javase/6/docs/api/java/util/Date.html#getYear%28%29

like image 130
Kal Avatar answered Oct 11 '22 17:10

Kal