Saturday, June 2, 2012

How to get all weekday[friday] for a month in C#

Sometimes I need Fridays of a month to do some calculation. I generally follow the following rules.
Lets say you have two combo box, one contains Year and another contains Months name.
When you select your desired year and month from the combo list, you want to get the days which contains Friday. Here is a simple code:

int selYr = Convert.ToInt32(comboYear.SelectedItem.ToString());
int selMn = comboMonth.SelectedIndex;
int[] holiday = new int[5];
int hIdx = 0;

int totalDays = DateTime.DaysInMonth(selYr, selMn);

DateTime currentDate;

for (int i = 1; i <= totalDays; i++)
          currentDate = new DateTime(selYr, selMn, i);
          if (currentDate.DayOfWeek == DayOfWeek.Friday)
                    holiday[hIdx++] = i;

After run this code block holiday array will contain that month's day of Friday. i.e. if you select 2012 as Year and May as Month then holiday will contain [4,11,18,25,0]. If you select June then holiday will contain [1,8,15,22,29]. 

No comments:

Post a Comment