16 December 2010

Get the date of the Nth day of a given year and weeknumber

Given a year and a weeknumber, you can calculate the date of the Nth day of that week. The best way to do this as far as I have been able to come up with is this:

public static DateTime GetNthDayOfWeek(int year, int weeknumber, int n, CultureInfo culture)
  // Get 1st jan of given year
  DateTime date = new DateTime(year, 1, 1);

  // Get the weeknumber of this 1st jan
  int beginWeek = GetWeekNumber(date, culture);
  if (beginWeek >= 52) beginWeek = 0;

  // determine how many weeks to jump ahead for the requested week
  int weeksToProgress = weeknumber - beginWeek;

  // Add this number of weeks
  date = culture.Calendar.AddWeeks(date, weeksToProgress);

  // move to nth day and return
  int dayOfWeek(int)culture.Calendar.GetDayOfWeek(date) - 
    (int)culture.DateTimeFormat.FirstDayOfWeek + 1;
  if(dayOfWeek <= 0) dayOfWeek += 7;
  return date.AddDays(n - dayOfWeek);

The GetWeekNumber method is of course the one as described in the post before this one.

No comments :