How to Get the number of weeks in a given year

illusion picture illusion · Jun 30, 2013 · Viewed 15.6k times · Source

Trying to code a correct function that returns the number of weeks in a given year, but without success.

Example of the function I'm looking for :

int weeks =  GetWeeksInYear ( 2012 )

should return 52 weeks // means there are only 52 weeks in 2012.

P.s.: in a year can be 52, 53, 54 weeks, not sure about 51

Answer

rene picture rene · Jun 30, 2013

See the Calendar.GetWeekOfYear method

public int GetWeeksInYear(int year)
{
      DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
      DateTime date1 = new DateTime(year, 12, 31);
      Calendar cal = dfi.Calendar;
      return  cal.GetWeekOfYear(date1, dfi.CalendarWeekRule, 
                                          dfi.FirstDayOfWeek);
}

Be carefull to figure out the correct CalendarWeekRule and FirstDayOfWeek for a Calendar that matches the culture your customers are used to. (for some calenders it might vary...)