Question

I recently asked this question, to take a list of datetime objects and parse out:

  1. Weekly Recurrence: Collections of dates that match the same dayOfWeek, hour, minute to get a set of lists where each item in the list matches that Key where:

    Key is concatenation of DayOfWeek + hour + minute

  2. Monthly Recurrence: Collections of dates that match the same weekOfMonth, dayOfWeek, hour, minute to get a set of lists where each item in the list matches that Key where:

    Key is concatenation of WeekOfMonth + DayOfWeek + hour + minute

both of these are working great.

I have an additional requirement now that I am struggling with to support bi weekly recurrence (every other week). I am trying to figure out the right key to match on that would work as both the other use cases above have logical computed key but can't figure the algorith / key for every other week

Was it helpful?

Solution

You'll need to figure out the week number for the date in question.

For example:

var dt = new DateTime(...); // your datetime
var cal = new System.Globalization.GregorianCalendar();
var weekNum = cal.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);

There are different strategies for counting weeks of the year, which you specify with a CalendarWeekRule and corresponding DayOfWeek for the starting day of the week. You can read more here.

Once you have a week number, you can do some math to make it "bi-weekly":

int biweeklyKey = weekNum % 2;

The value will be either 0 or 1, which you can use as a key in your algorithm.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top