SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd"); Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, 2014); cal.set(Calendar.MONTH, Calendar.DECEMBER); cal.set(Calendar.DAY_OF_MONTH, 31); Date d = cal.getTime(); System.out.println(sdf.format(d));
If you naively answered "2014-12-31", then I would tell you just this: you are really naive.
If you run this code under Java 6, you will get back an IllegalArgumentException, with the message "Illegal pattern character 'Y'". Now it might hit you that, indeed, the character for Year in a DateFormat is the lower case 'y'.
However, this code runs under Java 7, because the capital 'Y' was added to the DateFormat. But it does not stant for Year, but for Week Year. If, like me, you do not know what a Week Year is, here is the JavaDoc explanation:
A week year is in sync with a WEEK_OF_YEAR cycle. All weeks between the first and last weeks (inclusive) have the same week year value. Therefore, the first and last days of a week year may have different calendar year values. For example, January 1, 1998 is a Thursday. If getFirstDayOfWeek() is MONDAY and getMinimalDaysInFirstWeek() is 4 (ISO 8601 standard compatible setting), then week 1 of 1998 starts on December 29, 1997, and ends on January 4, 1998. The week year is 1998 for the last three days of calendar year 1997. If, however, getFirstDayOfWeek() is SUNDAY, then week 1 of 1998 starts on January 4, 1998, and ends on January 10, 1998; the first three days of 1998 then are part of week 53 of 1997 and their week year is 1997.
In short, my exemple code will print "2015-12-31", because the last days of the year belong to a week of the following year.