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!");}
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.