如何获得当年的总周数?[英] How to get the total number of weeks in the current year?

问题描述

我在stackoverflow上的代码下面,返回当年的一周总数,但它是在2014年和2016年不起作用的.我如何动态地获得每年的一周数???

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);

我这样做只是检查它是当前方法吗?

     Calendar cal = Calendar.getInstance();
     int year = cal.get(Calendar.YEAR);
     cal.set(Calendar.YEAR, year);
     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);

推荐答案

使用以下代码

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);

不在乎30,28和29天.每年的最后一天(任何一年)始终是12月31日.所以你需要那天举行. mCalendar.get(Calendar.WEEK_OF_YEAR)将返回当年的总周.


动态方式

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);

在上面代码中寻找错误.当您可以使用正常工作的代码

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;
    }

其他推荐答案

只需在此方法中使用当前年份:

int year = Calendar.getInstance().get(Calendar.YEAR);
cal.set(Calendar.YEAR, year);

休息与您的例子相同.

其他推荐答案

我有一个datepickerfragment,它的ondateset函数

public void onDateSet(DatePicker view, int year, int month, int day) {
    ((Main) getActivity()).setWeek(year, month, day);
} 

仅返回年,月和日.所以我必须做以下一周.

public void getWeek(int year, int month, int day){

        final Calendar c = Calendar.getInstance();
        c.set(year, month, day);
        int week = c.get(Calendar.WEEK_OF_YEAR);            

}

本文地址:https://www.itbaoku.cn/post/978686.html