“日历”类的“WEEK_OF_YEAR”属性可能对您有用。参考:日历类
创建一个新日期,该日期将是某个月的第一天。获取这一天的一年中的那一周,假设您获得了起始值。
创建一个新日期,该日期将是给定月份的最后一天。获取这一天的一周,所以现在你得到了结束值。
现在结束 - 开始+ 1应该是你想要的。
当一周与另一年或类似年份重叠时,您可能需要处理一些角落情况。但我认为,一旦你把这件事做好了,你就可以用简单的逻辑来做到这一点。
下面是一个简单的示例代码。我认为你可以让它成为功能,并传递任何你想要的东西。
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2013);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
int start = cal.get(Calendar.WEEK_OF_YEAR);
Log.d("BLA BLA", "Value is " + start);
cal.set(Calendar.YEAR, 2013);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 28);
int end = cal.get(Calendar.WEEK_OF_YEAR);
//Above line will not work for December Month, use following line for this
int end = isDecember?53:cal.get(Calendar.WEEK_OF_YEAR);
Log.d("BLA BLA", "Value is " + end);
Log.d("BLA BLA", "Num weeks:: " + (end - start +1 ));
对于角落情况:
角落情况只会发生在Januaray月份(例如2010年1月,2000年1月),在这些情况下,大多数日子都是前一年最后一周的一部分,因此起始值将为52,结束值将为5。发生这种情况时,请检查是否,
if(start > end) {
numweeks = end + 1;
}
P.S:把它放在你得到的不同测试输入中。让我知道,一旦你发现任何错误,我是否可以改进它。
甚至更简单的解决方案:
Calendar cal = Calendar.getInstance();
for(int i = 0 ; i < 11;i++){
cal.set(Calendar.YEAR, 2013);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, i);
int maxWeeknumber = cal.getActualMaximum(Calendar.WEEK_OF_MONTH);
Log.d("LOG","max week number" + maxWeeknumber);
}
01-22 01:49:03.591: D/LOG(573): max week number5
01-22 01:49:03.602: D/LOG(573): max week number5
01-22 01:49:03.602: D/LOG(573): max week number6
01-22 01:49:03.671: D/LOG(573): max week number5
01-22 01:49:03.671: D/LOG(573): max week number5
01-22 01:49:03.671: D/LOG(573): max week number6
01-22 01:49:03.681: D/LOG(573): max week number5
01-22 01:49:03.691: D/LOG(573): max week number5
01-22 01:49:03.691: D/LOG(573): max week number5
01-22 01:49:03.711: D/LOG(573): max week number5
01-22 01:49:03.711: D/LOG(573): max week number5
简单的解决方案适用于角落情况:
Calendar cal = Calendar.getInstance();
for(int i = 0 ; i < 11;i++){
cal.set(Calendar.YEAR, 2010);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, i);
int maxWeeknumber = cal.getActualMaximum(Calendar.WEEK_OF_MONTH);
// Month value starts from 0 to 11 for Jan to Dec
Log.d("LOG","For Month :: "+ i + " Num Week :: " + maxWeeknumber);
}
日志:
01-22 01:59:35.841: D/LOG(629): For Month :: 0 Num Week :: 6
01-22 01:59:35.841: D/LOG(629): For Month :: 1 Num Week :: 5
01-22 01:59:35.841: D/LOG(629): For Month :: 2 Num Week :: 5
01-22 01:59:35.841: D/LOG(629): For Month :: 3 Num Week :: 5
01-22 01:59:35.841: D/LOG(629): For Month :: 4 Num Week :: 6
01-22 01:59:35.852: D/LOG(629): For Month :: 5 Num Week :: 5
01-22 01:59:35.871: D/LOG(629): For Month :: 6 Num Week :: 5
01-22 01:59:35.871: D/LOG(629): For Month :: 7 Num Week :: 5
01-22 01:59:35.871: D/LOG(629): For Month :: 8 Num Week :: 5
01-22 01:59:35.871: D/LOG(629): For Month :: 9 Num Week :: 6
01-22 01:59:35.871: D/LOG(629): For Month :: 10 Num Week :: 5