How To: Get all Mondays in a given year in C##

I was working on small project today and one of the requirements is to list down all the Mondays in a year and populate a dropdownlist with the values.

It's a funny requirement but still needs to be done since the client wants it that way(Oh well, customer is always right even if it would end up wrong). Below is my 5 minute function that accepts a 4 digit year value and DayOfWeek as its parameter(I added this feature to the function just incase they go kookoo again). The function would then return a generic list of DateTime objects that equals the specified DyOfWeek(eg. DayOfWeek.Monday, DayOfWeek.Tuesday and etc.).

private List<DateTime> GetDatesByDayOfWeek(int selectedYear, DayOfWeek dayOfWeek)
{
   string firstDayOfTheYear = String.Format("January 1, {0}", selectedYear);
   string lastDayOfTheYear = String.Format("December 31, {0}", selectedYear);

   DateTime firstDateTime = DateTime.Parse(firstDayOfTheYear);
   DateTime lastDateTime = DateTime.Parse(lastDayOfTheYear);

   Int32 dayCount = lastDateTime.DayOfYear - 1;

   List<DateTime> selectedDates = new List<DateTime>();

   for (Int32 ctr = 0; ctr <= dayCount; ctr++) {
      DateTime processedDate = firstDateTime.AddDays(ctr);
      if (processedDate.DayOfWeek == dayOfWeek) {
         selectedDates.Add(processedDate);
      }
   }

   return selectedDates;
}

Pretty boring huh?

*update* Justice, the most Metrosexual developer in the face of North America posted a quick tweak to my code(Robert locke and Jokiz have the same comment too). Check his code below:

*update2* A bug was found by Robert Locke and Justice was kind enough to send the new code to fix the wrong block of code.

public static IList<DateTime> GetAllDaysOfWeekForYear(int year, DayOfWeek dw)
{
   List<DateTime > listOfDates = new List<DateTime>();

   DateTime firstDayOfWeekInYear = FindFirstDayOfWeekInYear(year, dw); 

   for (DateTime currentDateTime = firstDayOfWeekInYear; currentDateTime.Year == year;
currentDateTime = currentDateTime.AddDays(7))
   {
      listOfDates.Add(currentDateTime);
   }
   return listOfDates;
}

public static DateTime FindFirstDayOfWeekInYear(int year, DayOfWeek dw)

   for (int i = 1; i <= 7; ++i)
   {
      DateTime currentDate = new DateTime(year, 1, i);
      if (currentDate.DayOfWeek == dw)
      {
         return currentDate;
      }
   }
   throw new Exception("Impossible!");
}

Monday, August 27, 2007 11:53:02 PM (GMT Daylight Time, UTC+01:00) #    Comments [2]  | 

 

All content © 2010, Keith Rull
On this page
This site
Calendar
<August 2007>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
2627282930311
2345678
Archives
Sitemap
Blogroll OPML
Disclaimer

Powered by: newtelligence dasBlog 2.3.9074.18820

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

Send mail to the author(s) E-mail

Theme design by Jelle Druyts


Pick a theme: