Showing posts with label datetime. Show all posts
Showing posts with label datetime. Show all posts

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.

Get the culture specific weeknumber in .NET

The easiest way to get a culture specific weeknumber is the following:
culture.Calendar.GetWeekOfYear(inputDate, 
    culture.DateTimeFormat.CalendarWeekRule, 
    culture.DateTimeFormat.FirstDayOfWeek);

Where culture is the culture you wish to use for determining the weeknumber. To use the current culture, you can use the following:
CultureInfo culture = CultureInfo.CurrentCulture;