calculate number of weeks in a given year

前端 未结 9 2207
北恋
北恋 2020-12-04 01:48

I would like to get the number of weeks in any given year. Even though 52 is accepted as a generalised worldwide answer, the calendars for 2015,

9条回答
  •  青春惊慌失措
    2020-12-04 02:23

    For ISO date format, we can calculate number of weeks as follows:

    int getNoOfWeeks(int year) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.setMinimalDaysInFirstWeek(4);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        return cal.getActualMaximum(Calendar.WEEK_OF_YEAR);
    }
    

    So, for year = 2018, it will return 52, for 2019, it will also return 52, but for 2020 it will return 53 as ISO year has 52 or 53 weeks.

提交回复
热议问题