这是使用日历 API 的一种方法:
private static final Calendar START_CAL = createAugust26th2012Cal();
public int getWeekNumber(Calendar someCal) {
int theWeek = someCal.get(Calendar.WEEK_OF_YEAR);
int weekCount = 0;
while (theWeek != START_CAL.get(Calendar.WEEK_OF_YEAR)) {
someCal.add(Calendar.WEEK_OF_YEAR, -1);
theWeek = someCal.get(Calendar.WEEK_OF_YEAR);
weekCount++;
}
return weekCount;
}
或者您可以获取两个日历之间的差异(以毫秒为单位),然后将结果除以一周中的毫秒数:
如果您使用这种方法,请不要忘记考虑 TimeZones 和 Daylight Saving Time。
我不记得确切的代码是什么样子来补偿 DST,但我认为它是这样的:(
我不太记得是添加偏移量还是从两个操作数中减去偏移量)
private static final long ONE_WEEK_MILLIS = 1000 * 60 * 60 * 24 * 7;
public int getWeeksBetween(Calendar calOne, Calendar calTwo) {
long millisOne = calOne.getTime().getTime();
long millisTwo = calTwo.getTime().getTime();
long offsetOne = calOne.getTimeZone().getOffset(millisOne);
long offsetTwo = calTwo.getTimeZone().getOffset(millisTwo);
long diff = (millisTwo - offsetTwo) - (millisOne + offsetOne );
return diff / ONE_WEEK_MILLIS;
}