I have following code to get different parts of current system Date (10-11-2011 for this case).
Calendar now = Calendar.getInstance();
String dt = ""+now.get(now.DATE)+"-"+now.get(now.MONTH)+"-"+now.get(now.YEAR);
Here, DATE and YEAR fields are giving values as expected but MONTH field is giving unexpected results, firstly I didn't knew that MONTH field starts with zero, so having current month as 11 will give me 10. Now, if I use now.get(now.MONTH+1) than it returns 46. And using simply now.MONTH instead of using get method gives 2.
So, what am I doing wrong here? it shouldn't be a bug in Calendar class.
Note that I'm using JDK 7.
解决方案
You need now.get(Calendar.MONTH) + 1.
now.get(Calendar.MONTH) returns the month starting at 0. And you need to add 1 to the result. If you do now.get(Calendar.MONTH + 1), you're getting something other than the month, because you don't pass the MONTH constant to the get method anymore. get just takes an int as parameter. The constant MONTH means "I want to get the month". The constant DATE means "I want to get the date". Their value has no meaning. MONTH is 2, and 3 is WEEK_OF_YEAR.
Also note that static variables (or constants) should be accessed using the class name, and not an instance of the class.
Have you considered using SimpleDateFormat? That's the class to use to format a Date using a specific pattern:
new SimpleDateFormat("dd/MM/yyyy").format(now.getTime());