Here's one approach using the calendar 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; }
Or you can get diff (in milliseconds) between two calendars and divide the result by the number of milliseconds per week:
If you use this approach, do not forget to consider TimeZones and daylight saving time.
I canβt remember exactly what the code for DST compensation looks like, but I think itβs something like this: (I canβt remember whether the offset was added or the offset was subtracted from the two operands)
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; }
source share