Search code examples
javadatecalendargregorian-calendar

Why is Calendar class (Java) resetting its fields?


I am trying to set properties for a Calendar class instance. But each time I get to Dec 30, it resets to the next year. Is this a draw in the Calendar class?

public Calendar setCalendar()
{
    String Date = "2013-12-30";
    int yyyy = Integer.parseInt(date.substring(0,4));
    int mm = Integer.parseInt(date.substring(5,7));
    int dd = Integer.parseInt(date.substring(8,10));
    System.out.println(yyyy + " " + mm + " " + dd);
    Calendar Cal= new GregorianCalendar();
    Cal.set(yyyy,mm,dd);
    System.out.println(Cal.get(Calendar.YEAR)+","+Cal.get(Calendar.MONTH));

    return Cal;
}

Output: 2013 12 30 2014,0


Solution

  • With Calendar the months are 0-based, so you're actually setting the month to next year's January.

    If you really need to use a Calendar I recommend at least using a SimpleDateFormat to parse your String to a Date and setting the calendar using that.