algorithm for calculating a week # from a date with custom start of week? (for iCal)

5.3k views Asked by At

I can only find algorithm for getting ISO 8601 week (week starts on a Monday).

However, the iCal spec says

A week is defined as a seven day period, starting on the day of the week defined to be the week start (see WKST). Week number one of the calendar year is the first week that contains at least four (4) days in that calendar year.

Therefore, it is more complex than ISO 8601 since the start of week can be any day of the week.

Is there an algorithm to determine what is the week number of a date, with a custom start day of week?

or... is there a function in iCal4j that does this? Determine a weekno from a date?

Thanks!

p.s. Limitation: I'm using a JVM language that cannot extend a Java class, but I can invoke Java methods or instantiate Java classes.

2

There are 2 answers

1
Henry On BEST ANSWER
  1. Let daysInFirstWeek be the number of days on the first week of the year that are in January. Week starts on a WKST day. (e.g. if Jan 1st is a WKST day, return 7)

  2. Set dayOfYear to the n-th days of the input date's year (e.g. Feb 1st = 32)

  3. If dayOfYear is less than or equal to daysInFirstWeek

    3.1. if daysInFirstWeek is greater than or equal to 4, weekNo is 1, skip to step 5.

    3.2. Let daysInFirstWeekOfLastYear be the number of days on the first week of the previous year that are in January. Week starts on a WKST day.

    3.3. if daysInFirstWeekOfLastYear is 4 or last year is Leap year and daysInFirstWeekOfLastYear is 5, weekNo is 53, otherwise weekNo is 52, skip to step 5.

  4. Set weekNo to ceiling((dayOfYear - daysInFirstWeek) / 7)

    4.1. if daysInFirstWeek greater than or equal to 4, increment weekNo by 1

    4.2. if daysInFirstWeek equal 53 and count of days on the first week (starting from WKST) of January in the year of inputDate's year + 1 is greater than or equal to 4, set weekNo to 1

  5. return weekNo

3
vkoo On
if (input_date < firstDateOfTheYear(WKST, year))
{
    return ((isLeapYear(year-1))?53:52);
}
else
{
    return ((dayOfYear(input_date) - firstDateOfTheYear(WKST, year).day)/7 + 1);
}

firstDateOfTheYear returns the first calendar date given a start of week(WKST) and the year, e.g. if WKST = Thursday, year = 2012, then it returns Jan 5th.

dayOfYear returns sequencial numerical day of the year, e.g. Feb 1st = 32

Example #1: Jan 18th, 2012, start of week is Monday

  • dayOfYear(Jan 18th, 2012) = 18
  • firstDateOfTheYear(Monday, 2012) = Jan 2nd, 2012

(18 - 2)/7 + 1 = 3 Answer Week no. 3

Example #2: Jan 18th, 2012, start of week is Thursday

  • dayOfYear(Jan 18th, 2012) = 18
  • firstDateOfTheYear(Thursday, 2012) = Jan 5th, 2012

(18 - 5)/7 + 1 = 2 Answer Week no. 2

Example #3: Jan 1st, 2012, start of week is Monday

  • firstDateOfTheYear(Monday, 2012) = Jan 2nd, 2012
  • IsLeapYear(2012-1) = false

Jan 1st, 2012 < Jan 2nd, 2012 Answer Week no. 52