Java Calendar bug when set date is 30/12 or 31/12

Minh Nguyen :

I use class Calendar to create Date. But in my test case when i set date is 31/12 or 30/12, year of my date is my set year of date + 1. Example 2018-12-29 -> 2018-12-29 but 2018-12-30 -> 2019-12-30. I don't know why ? My code:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class MyClass {
    public static void main(String args[]) {
        calendarBug(2018, 11, 29);
        calendarBug(2018, 11, 30);
    }

    public static void calendarBug(int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month);
        calendar.set(Calendar.DAY_OF_MONTH, day);
        Date date = calendar.getTime();
        System.out.println(new SimpleDateFormat("YYYY-MM-dd").format(date));
    }
}

Output:

2018-12-29
2019-12-30
Cà phê đen :

YYYY represents for week year. Use yyyy instead.

From javadocs:

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=112093&siteId=1