Tuesday, July 25, 2006

 

Date Calculations - How to Compute Weeks?


Although everyone would probably agree that the DateTime object exposes extremely useful functionality, many people wonder why they have not included methods or properties to determine if a date on the same week than another or two weeks away or what be it.

So a lot of people go and create lots of complicated date algorithms and make it available on the net for people to plug into their code. While very altruistic, unfortunately their efforts are in vain. That is because .Net does include functionality to deal with weeks, it's just that this functionality is not in the DateTime object...it's in the CultureInfo class!

You might be wondering why in hell that is so. Well, it's very simple really. The concept of a week changes depending on the country. Some countries consider it to start on Sunday, others on Monday, for example. So the determinant of a week is both the date and the country you're in.

So, if you want to, say, compare if a date1 is on the same week as date2 this is what you should do:


C#
using System.Globalization;

CultureInfo cult = CultureInfo.CurrentCulture;
int date1WeekNo = cult.Calendar.GetWeekOfYear(date1);
int date2WeekNo = cult.Calendar.GetWeekOfYear(date2);

//now you have the number of the week for both dates in the current year
//all you need to do now is simple comparisson
if (date1WeekNo == date2WeekNo)
//same week; do something


So, first we get a CultureInfo object based on the current culture we're in. Inside the CultureInfo object you will find anothe object called Calendar which has many methods for manipulating dates but automatically taking into context the current culture you're working in. One of these niceties is the GetWeekOfYear() method which takes a date and automatically gives you what week number that date is in the current year. You can do this for every date you want and then it all becomes simple arithmetic. You can just take the difference between two week numbers, for instance, and find out how many weeks ago or ahead one date is from another. Simple, huh?

The nice thing about this approach is that you don't even need to know what week system the culture you're working in uses. It all happens automagically for you!

So next time you need a date function you can't find in DateTime, look first on CultureInfo.Calendar and you might just save yourself a lot of coding!


Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?