编程语言
首页 > 编程语言> > java-如何获取当年的总周数?

java-如何获取当年的总周数?

作者:互联网

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

标签:android-calendar,android,java
来源: https://codeday.me/bug/20191010/1886331.html