Extension Method From The Trenches – C# Week Of Year
Currently I am working in a slightly different capacity to what I am used to…. what I consider to be…. working in the trenches (basically getting involved in the day to day nitty gritty). Today I discovered there was no easy way to get the week number from a DateTime (I really expected there to be a WeekOfYear property on DateTime but there is not. Luckily it is a pretty easy to work this information out.
namespace DateTimeWeekYearExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(new DateTime(2010, 01, 01).GetWeekNumber()); //Friday 01 January 2010 - Week 1
Console.WriteLine(new DateTime(2010, 01, 03).GetWeekNumber()); //Sunday 03 January 2010 - Week 2
Console.Read();
}
}
public static class DateHelpers
{
public static int GetWeekNumber(this DateTime source)
{
return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(source,
CalendarWeekRule.FirstDay,
DayOfWeek.Sunday);
}
}
}
The great thing about the GetWeekOfYear method that hangs off of the culture information's calendar is that you can configure which day is the first day of the week as well as the calendar week rule.
Thursday, 27th May, 2010 By Daniel Watson (c#, calender)