Change the first week of the year

Using Java Calendar or something else, let's say I set the date to 2012-10-26. I want this date to be the first day of the year. Is it possible to get the week number of a certain date - say, it's 2012-12-10- Assuming that the first week of the year starts from 2012-10-26?

I know that my question sounds a little strange, but I could use any useful input.

Thanks.

- Details

I have a database table called WeeklySchedule. In this table, I have columns starting from week from week to week52, and each column contains some data about the days of this week. Unfortunately, Week1 is not the first week of the year. I need to do my calculations, assuming that Week1 starts from 2012-08-26.

+6
source share
2 answers

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; } 
+2
source

I have never seen a built-in function for this, only calls like Calendar.get(WEEK_OF_YEAR) or Joda LocalDate.getWeekOfWeekyear() . java.util.Calendar (and Date ) is often seen as a poor library compared to a library such as Joda Time. This SO post has a good list of pros and cons.

Please note that if the database table is applied year after year, repeated after year, you may run into problems. Several years ( 71 years for 400, or about 1 each 5.6 ) have 53 weeks.

Given the above, you may need to get closer, for example, to calculate the number of days between two dates , divided by 7 (all mod 52), which will slide by a small amount each year or calculate (weekOfYear(date) - weekOfYear(startDate)) % 52 , which can be repeated during the week at the beginning of the calendar year.

+1
source

All Articles