j-nunn.com

Working with weeks in c#

    The .net framework provides some great date time features, some of which are culture specific. however the support for the week is only half there.

    You can easily get the week number for a given date using the following bit of code:

int WeekNumber = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(MyDate, 
                                 CalendarWeekRule.FirstFourDayWeek, 
                                 DayOfWeek.Monday);

However to get the first day of that week is a little harder:

int diff = CultureInfo.CurrentCulture.Calendar.GetDayOfWeek(MyDate) - DayOfWeek.Monday; 
DateTime firstDate = MyDate.AddDays(-diff);

If you want to get the first day of the week when all you have is the week number and year then there are quite a few steps:

DateTime FirstWeek = DateTime.Parse(String.Format("1/1/{0}", MyYear.ToString()));
DateTime ThisWeek = CultureInfo.CurrentCulture.Calendar.AddWeeks(FirstWeek, MyWeekNumber);
int diff = CultureInfo.CurrentCulture.Calendar.GetDayOfWeek(ThisWeek) - DayOfWeek.Monday;
DateTime firstDate = ThisWeek.AddDays(-diff);

Post a comment

  1. Formatting options
       
     
     
     
     
       
Copyright © 2010 John Nunn
This site is powered by