views:

48

answers:

3

I have a

startdate 2010-01-01 (I just assume its a first day of the week)

and an

enddate 2010-07-31 (I just assume its a first day of the week)

I want to have returned from a method all week numbers for every first day of the week for the

above timespan. I can not assume that the first day of week is always monday, because my user

could be from Sweden, USA or whereever. The algorythm should be compatible with ISO 8601.

The final result should look roughly like this:

2010-01-01 , 1
2010-01-08 , 2
2010-01-15 , 3
2010-01-22 , 4
...
2010-07-31 , ~28

Yes I know google is full of links about that topic but nobody is doing it right. They all

assume that monday is first day of a week. Maybe some of the c# gods on SO pass by :P

EDIT:

What do you say to this code:

public static int GetWeekNumber(DateTime dtPassed)
        {
            CultureInfo ciCurr = CultureInfo.CurrentCulture;
            int weekNum = ciCurr.Calendar.GetWeekOfYear(dtPassed, CalendarWeekRule.FirstDay, DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek);
            return weekNum;
        }

I found it partly on google and changed it a bit.

+1  A: 
var week = new DateTime(2010, 1, 1).AddDays(7 * i);
Console.Out.WriteLine("week = {0}", week);

Where i is the number of the week you want. Since it is a DateTime type you can do whatever you want with it by locale. It would take just a little bit of work of handling leap years. You could use DateTime.IsLeapYear() to detect if it is a leap year, and add an addition day if the date is past 2/29.

vcsjones
+1  A: 

You might want to take a look at CultureInfo.CurrentCulture.Calendar.GetWeekOfYear

Edit:

Small fix for your own example, plus making it an extension so it's easier to use ;)

public static int GetWeekNumber(this DateTime dtPassed)
{
    CultureInfo ciCurr = CultureInfo.CurrentCulture;
    DateTimeFormatInfo fiCurr = DateTimeFormatInfo.CurrentInfo;
    int weekNum = ciCurr.Calendar.GetWeekOfYear(dtPassed, fiCurr.CalendarWeekRule, fiCurr.FirstDayOfWeek);
    return weekNum;
}

the this infront of DateTime allows you to use it as if it's a function for a DateTime object..

so you could do

int week = DateTime.Now.GetWeekNumber();
Doggett