jantox
jantox

Reputation: 2185

Error in parsing date

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);

Upvotes: 1

Views: 113

Answers (1)

Bohemian
Bohemian

Reputation: 424953

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.

Upvotes: 5

Related Questions