KSHiTiJ KSHiTiJ - 3 months ago 5x
Java Question

java date issue in getting month and year

i am getting problem from extracting month and year from data object.

String strdate = "2012-11-07T13:28:23";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// Date date = dateFormat.parse(strdate);
Date date = new Date();

my output is like

Wed Nov 28 15:37:30 IST 2012

what is wrong here ?


what is wrong here ?

Your compiler should be telling you what's wrong via warnings: you're using deprecated methods on Date, to start with. Don't ignore those warnings.

You should be using Calendar to get day/month/year etc values, as a Calendar has an associated calendar system and time zone, both of which are required in order to get sensible values out.

Next there's the problem that you're just getting the current date and time instead of using strdate and dateFormat:

// Date date = dateFormat.parse(strdate);
Date date = new Date();

new Date() always returns the current date/time as reported by the system.

However, if you're confused by the 112 and the 10, you should read the documentation for the methods you're calling, which explains that getYear() returns a year based on 1900 (so a return value of 112 means the year is 2012), and getMonth() returns a 0-based month (so January=0). Always read the documentation for methods you're calling, especially if you think they're giving you odd results.

Ideally, however, you should use Joda Time instead - it's a far more sensible date/time API than the built-in one.