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

前端 未结 7 1823
野的像风
野的像风 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:55

    Use the below code

    Calendar mCalendar = new GregorianCalendar(); 
    mCalendar.set(Calendar.YEAR, 2014); // Set only year 
    mCalendar.set(Calendar.MONTH, Calendar.DECEMBER); // Don't change
    mCalendar.set(Calendar.DAY_OF_MONTH, 31); // Don't change
    int totalWeeks = mCalendar.get(Calendar.WEEK_OF_YEAR);
    

    Don't care about 30, 28 and 29 days of month. Last day of a year (Any year) is always 31 Dec. So you need to set that day. And mCalendar.get(Calendar.WEEK_OF_YEAR) will return the total weeks in that year.


    Update for dynamic way

    private int getTotalWeeksInYear(int year) {
            Calendar mCalendar = new GregorianCalendar(); 
            mCalendar.set(Calendar.YEAR, year); // Set only year 
            mCalendar.set(Calendar.MONTH, Calendar.DECEMBER); // Don't change
            mCalendar.set(Calendar.DAY_OF_MONTH, 31); // Don't change
            return mCalendar.get(Calendar.WEEK_OF_YEAR);
        }
    
        // Call as
        int totalWeeks = getTotalWeeksInYear(2014);
    

    Looking for bug in above code. By the time you can use below code that is working fine

    private int getTotalWeeksInYear(int year) {
            Calendar mCalendar = new GregorianCalendar(TimeZone.getDefault()); 
            mCalendar.setFirstDayOfWeek(Calendar.MONDAY);
            // Workaround
            mCalendar.set(year, 
                    Calendar.DECEMBER, 
                    31);
            int totalDaysInYear = mCalendar.get(Calendar.DAY_OF_YEAR);
            System.out.println(totalDaysInYear);
            int totalWeeks = totalDaysInYear / 7; 
            return totalWeeks;
        }
    

提交回复
热议问题