Writing a GetFirstDayOfWeek(int week, int year) function

It took me some time to write a DateTime GetFirstDayOfWeek(int week, int year) function yesterday. I’m not going to say HOW long it took me but just…I HATE date calculations. This should be a built in .NET feature!

Hopefully this will ease the pain of someone out there!

public static class DateHelper
	{		

		public static DateTime GetFirstDayOfWeek(int week, int year)
		{
			ThrowExceptionOnInvalidWeek(week);
			return GetFirstDayOfFirstWeek(year).AddDays((week - 1) * 7);
		}

		private static void ThrowExceptionOnInvalidWeek(int week)
		{
			if (week < 1 || week > 54)
			{
				throw new ArgumentException("the week must be within 1 and 54");
			}
		}

		private static DateTime GetFirstDayOfFirstWeek(int year)
		{
			DateTime firstDayOfYear = new DateTime(year, 1, 1);
			DateTime firstDayOfFirstWeek = new DateTime(year, 1, 1);			

			if (firstDayOfYear.DayOfWeek == DayOfWeek.Monday)
			{
				firstDayOfFirstWeek = firstDayOfYear;
			}
			else if (firstDayOfYear.DayOfWeek == DayOfWeek.Tuesday)
			{
				firstDayOfFirstWeek = firstDayOfYear.AddDays(-1);
			}
			else if (firstDayOfYear.DayOfWeek == DayOfWeek.Wednesday)
			{
				firstDayOfFirstWeek = firstDayOfYear.AddDays(-2);
			}
			else if (firstDayOfYear.DayOfWeek == DayOfWeek.Thursday)
			{
				firstDayOfFirstWeek = firstDayOfYear.AddDays(-3);
			}
			else if (firstDayOfYear.DayOfWeek == DayOfWeek.Friday)
			{
				firstDayOfFirstWeek = firstDayOfYear.AddDays(-4);
			}
			else if (firstDayOfYear.DayOfWeek == DayOfWeek.Saturday)
			{
				firstDayOfFirstWeek = firstDayOfYear.AddDays(-5);
			}
			else if (firstDayOfYear.DayOfWeek == DayOfWeek.Sunday)
			{
				firstDayOfFirstWeek = firstDayOfYear.AddDays(-6);
			}
			return firstDayOfFirstWeek;
		}

	}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s