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

### 问题描述

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

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

## 其他推荐答案

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

## 其他推荐答案

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

}
```