DevPinoy.org
A Filipino Developers Community
   
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!");
}


Posted 08-27-2007 3:35 PM by keithrull

Comments

lamia wrote re: How To: Get all Mondays in a given year in C#
on 08-27-2007 4:53 PM

Not too boring at all... :)

Robert Locke wrote re: How To: Get all Mondays in a given year in C#
on 08-27-2007 5:38 PM

Cool... I suppose one quick optimization would be to increment by 7 once you've found the first Monday (or whatever) of the year. =)

jokiz wrote re: How To: Get all Mondays in a given year in C#
on 08-27-2007 6:44 PM

agree with robert

keithrull wrote re: How To: Get all Mondays in a given year in C#
on 08-27-2007 9:03 PM

yup, i thought about that roo robert and jokiz. less cpu cycles on our loop.

Robert Locke wrote re: How To: Get all Mondays in a given year in C#
on 08-29-2007 12:28 AM

Nice!  I've never actually coded in C#, but in FindFirstDayOfWeekInYear, the for-loop doesn't seem to use the variable "i".  Should that be: new DateTime(year, 1, i), perhaps?

I'm also guessing that in "GetAllDaysOfWeekForYear", that "firstDayOfWeekInYear" gets added twice.  Once here:

  listOfDates.Add(firstDayOfWeekInYear);

and once more during the first iteration of the for-loop.

I could be wrong though! =)

jakelite wrote re: How To: Get all Mondays in a given year in C#
on 08-29-2007 7:12 AM

you might want to cache the results somewhere say a file or in a database. and have it named/keyed by year. that way you need to run the function only once when its not in the cache ala singleton.

cheers!

Justice~! wrote re: How To: Get all Mondays in a given year in C#
on 08-29-2007 9:19 AM

No, you're right Robert!!  It turns out that optimizations only work if the developer who suggests them (yours truly) isn't totally incompetent.  ;)

CryptoKnight wrote re: How To: Get all Mondays in a given year in C#
on 09-01-2007 9:17 PM

Hi Keith,

Here's another optimization to get the first day of the year without looping...

       private DateTime FindFirstDayOfWeekInYear(int year, DayOfWeek dw)

       {

           DateTime dt = new DateTime(year, 1, 1);

           int firstDayOfYear = (int)dt.DayOfWeek;

           double addDays = (7 + (int)dw - firstDayOfYear) % 7;

           return dt.AddDays(addDays);

       }

cheers!

keithrull wrote re: How To: Get all Mondays in a given year in C#
on 09-02-2007 9:11 AM

Nice one CryptoKnight! Now thats a real solution ;)

Copyright DevPinoy 2005-2008