Monday, June 26, 2006

Date Manipulation - GoToWeek and WeekOfYear (C#)

GoToWeek goes to the specific week in a year (e.g. GoToWeek(2006, 10) would go return the start day of week 10 in 2006 - 27th February). WeekOfYear returns the given dates Week Number (e.g. GoToWeek(DateTime.Now) would return 27). Uses the current threads culture, so will work with whatever culture you have set the current thread to (e.g. System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-GB");).

private DateTime GoToWeek(int year, int week)
{
 // use the current culture
 System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
 // get first day of week from culture
 DayOfWeek fdow = ci.DateTimeFormat.FirstDayOfWeek;
 
 // new empty Date (so starts 01/01/0001)
 DateTime d = new DateTime();
 
 // year starts at 1, so take away 1 from desired year to prevent going to the next one
 d = d.AddYears(year - 1);
 
 // get day January 1st falls on
 int startDay = (int)d.DayOfWeek;
 
 // get the difference between the first day of the week, and the day January 1st starts on
 int difference = (int)fdow - startDay;
 // if it is positive (i.e. after first day of week), take away 7
 if(difference > 0)
 {
  difference = difference - 7;
 }
 
 // already on week 1, so add desired number of weeks - 1 * days in week
 if(week > 1)
 {
  d = d.AddDays((week - 1) * 7 + difference);
 }
 
 return d;
}

private int WeekOfYear(DateTime date)
{
 // use the current culture
 System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
 // use current culture's calendar
 System.Globalization.Calendar cal = ci.Calendar;
 // get the calendar week rule (i.e. what determines the first week in the year)
 System.Globalization.CalendarWeekRule cwr = ci.DateTimeFormat.CalendarWeekRule;
 // get the first day of week for the current culture
 DayOfWeek fdow = ci.DateTimeFormat.FirstDayOfWeek;
 // return the week
 return cal.GetWeekOfYear(date, cwr, fdow);
}

Tags: , , , ,

No comments: