Posted by: Cirilo Meggiolaro | 02/25/2009

Tip of the day #134 – Getting the week of the year

Quick tip for this cold Wednesday: how to get an integer value with the week of the year that a specific date belongs to.

For this tip we are going to use the GregorianCalendar class under the System.Globalization namespace.

How to…

Create a new instance of the GregorianCalendar class. The following constructors are available:

public GregorianCalendar();

public GregorianCalendar(GregorianCalendarTypes type);

Consume the method GetWeekOfYear. The following method signature is available:

public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek);

The method accepts a DateTime object as the date to be checked, a CalendarWeekRule enumerator that defines how the first week of the year is defined (by the first day of the year, by the first full week or by the first week with four or more days) and a DayOfWeek enumerator that defines what is the first day of the week.

The following code snippet shows how to retrieve the week of the year using the first day of the year as the start rule, and Sunday as the first day of the week:

GregorianCalendar calendar = new GregorianCalendar();

Console.WriteLine(“Week of the year: “ + calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay, DayOfWeek.Sunday));

Output for 02/25/2009

Week of the year: 9

Bad news: The summer only starts within 17 weeks in North America.

Advertisements

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

Categories

%d bloggers like this: