Calendar 类的 WEEK_OF_YEAR 属性对您很有用。参考:日历类
创建一个新日期,该日期将是某个月份的第一天。获取这一天的一年中的一周,假设您获得了起始值。
创建一个新日期,该日期将是给定月份的最后一天。获取这一天的一年中的一周,所以现在你得到了最终值。
现在 end - start + 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;
}
PS:把它放到你得到的不同的测试输入中。如果您发现任何错误,请告诉我是否可以改进。
甚至更简单的解决方案:
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