1

I have the following code. The problem occurs when getting the month. It says 'The 'month' argument must be in the range 1 to 12.' and it always return 0. Why?

    String target = "2013-01-04";
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    Date date = df.parse(target);

   Calendar cal = Calendar.getInstance();
   cal.setTime(date);
   int year = cal.get(Calendar.YEAR);
   System.out.println("year-"+year);
   int month = cal.get(Calendar.MONTH);
   System.out.println("month-"+month);
   int day = cal.get(Calendar.DAY_OF_MONTH);
   System.out.println("day-"+day);
3
  • read the javadoc...month is 0-based (i.e. January=0 and December=11). Commented Jan 11, 2013 at 3:27
  • ok thanks. so i should add +1 everytime. Commented Jan 11, 2013 at 3:30
  • if you really want to..i'm not the one writing the code. Commented Jan 11, 2013 at 3:31

1 Answer 1

5

This is a quirk of the Calendar class. For some insane reason, it uses a zero-based index for months, even though all other date parts are one-based.

Don't even think about raising an issue about this, as you'll join a long line of people: Calendar is arguably the most broken class in the JDK.

The "fix" is to use the jodatime library, which is great for all your date manipulation, parsing and formatting needs. It's practically the industry standard now.

Sign up to request clarification or add additional context in comments.

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.