Why Java Calendar set(int year, int month, int date) not returning correct date?

JavaCalendar

Java Problem Overview


According to doc, calendar set() is:

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html#set%28int,%20int,%20int%29

set(int year, int month, int date) 
Sets the values for the calendar fields YEAR, MONTH, and DAY_OF_MONTH.

code:

Calendar c1 = GregorianCalendar.getInstance();
c1.set(2000, 1, 30);  //January 30th 2000
Date sDate = c1.getTime();

System.out.println(sDate);

output:

Wed Mar 01 19:32:21 JST 2000

Why it's not Jan 30 ???

Java Solutions


Solution 1 - Java

1 for month is February. The 30th of February is changed to 1st of March. You should set 0 for month. The best is to use the constant defined in Calendar:

c1.set(2000, Calendar.JANUARY, 30);

Solution 2 - Java

Months in Calendar object start from 0

0 = January = Calendar.JANUARY
1 = february = Calendar.FEBRUARY

Solution 3 - Java

Selected date at the example is interesting. Example code block is:

Calendar c1 = GregorianCalendar.getInstance();
c1.set(2000, 1, 30);  //January 30th 2000
Date sDate = c1.getTime();

System.out.println(sDate);

and output Wed Mar 01 19:32:21 JST 2000.

When I first read the example i think that output is wrong but it is true:)

  • Calendar.Month is starting from 0 so 1 means February.
  • February last day is 28 so output should be 2 March.
  • But selected year is important, it is 2000 which means February 29 so result should be 1 March.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMeowView Question on Stackoverflow
Solution 1 - JavaBenoit ThieryView Answer on Stackoverflow
Solution 2 - JavafmucarView Answer on Stackoverflow
Solution 3 - JavaerhunView Answer on Stackoverflow