How to get the total number of weeks in the current year?

前端 未结 7 1860
野的像风
野的像风 2021-01-17 09:24

I got below code on stackoverflow which return total number of week in current year, but it is hardcoded which\'ll not work on 2014 and 2016. How I get total number of week

7条回答
  •  [愿得一人]
    2021-01-17 09:48

    You can use something like

    private Calendar getCalendar(int year, int month, int day) {
        Calendar calendar = Calendar.getInstance(Locale.GERMAN);
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.set(year, month, day);
        return calendar;
    }
    
    private int getTotalWeeksInYear(int year) {
        return getCalendar(year, Calendar.DECEMBER, 31).get(Calendar.WEEK_OF_YEAR); 
    }
    

    Remember that definition of Week of Year is local dependent. It means that in different locales returned value of get(Calendar.WEEK_OF_YEAR) will be different. For example in Locale.GERMAN according to DIN 1355-1 / ISO 8601 the first Week of Year is the week contains 4 or more days in the new year. For the Locale.US the first Week of Year is the week where the 1 January belongs to.

提交回复
热议问题