ayo alatishe
ayo alatishe

Reputation: 47

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

Upvotes: 1

Views: 64

Answers (2)

Phuthib
Phuthib

Reputation: 1446

Check the Calendar API doc, month value is 0 based i.e Jan is 0.

month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.

You are setting month to 12. This effectively gives you the next year. To correct try:

Cal.set(yyyy,mm-1,dd);

Hope that helps

Upvotes: 0

Kayaman
Kayaman

Reputation: 73568

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.

Upvotes: 3

Related Questions