OK, so I did some research into this and found there's an ISO standard
for defining Week 1 of any given year and for defining the first day of
the week. See the url below for more details:
http://www.iso.ch/iso/en/prods-services/popstds/datesandtime.html?printable=true
Using this, I came up with the following algorithm:
// Calculates the Week Number in accordance to ISO-8601
public int GetWeekNumber(DateTime dt)
{
int year = dt.Year;
// Check that the date is or is after December 29.
if (dt >= new DateTime(year, 12, 29))
{
week1 = GetWeekOneDate(year + 1);
if (dt < week1)
{
week1 = GetWeekOneDate(year);
}
}
else
{
week1 = GetWeekOneDate(year);
if (dt < week1)
{
week1 = GetWeekOneDate(--year);
}
}
return ((dt - week1).Days / 7 + 1);
}
public DateTime GetWeekOneDate(int year)
{
// Get the date for Jan-4 for the given year
DateTime date = new DateTime(year, 1, 4);
// Get the ISO-8601 day number for this date 1==Monday, 7==Sunday
int dayNum = (int)date.DayOfWeek; // 0==Sunday, 6==Saturday
if(dayNum == 0)
dayNum = 7;
// Return the date of the Monday that is less than or
// equal to this date
return date.AddDays(1 - dayNum);
}
--
Neil Cowburn, MVP
Co-founder, OpenNETCF.org
Technologist, Content Master Ltd
Microsoft .NET Compact Framework MVP
www.opennetcf.org |
www.contentmaster.com