calculate number of weeks in a given year

前端 未结 9 2208
北恋
北恋 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:03

    According to the wikipedia article on ISO week date format, You can calculate it using following code.

        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, 2015);
        cal.set(Calendar.MONTH, Calendar.DECEMBER);
        cal.set(Calendar.DAY_OF_MONTH, 31);
    
        int ordinalDay = cal.get(Calendar.DAY_OF_YEAR);
        int weekDay = cal.get(Calendar.DAY_OF_WEEK) - 1; // Sunday = 0
        int numberOfWeeks = (ordinalDay - weekDay + 10) / 7;
        System.out.println(numberOfWeeks);
    

    Update:

    Seems the answer from @Samuel https://stackoverflow.com/a/40174287/201986 is better and free from the bug mentioned by Luca

提交回复
热议问题