views:

232

answers:

3

Hey,

I have made a function to cound the weeks in a year, and that works fine. The problem is that I need a method to get the mondaydate of the week. This is a swedish calendar.

The code below works well for years that have 52 weeks, but some years(like 2009) has 53 weeks. Then I got a date from januari as the mondaydate(cant be right). So please help me to get it to work for all years.

What I probably could do is check if the year has 53 weeks and then do some checks but I'd like it to go smooth without special checks.

Here's what I've come up with:

    public static DateTime GetDateFromWeek(int year, int week)
    {
        //First day of the year
        DateTime d = new DateTime(year, 1, 1);
        GregorianCalendar calendar = new GregorianCalendar(GregorianCalendarTypes.MiddleEastFrench);
        d = calendar.AddWeeks(d, week);
        d = d.AddDays(1 - (double)d.DayOfWeek);
        return d;
    }
A: 

You might want to have a look at the following question, I think it is what you are asking:

http://stackoverflow.com/questions/1665832/get-date-of-first-day-of-week

Paddy
+2  A: 

I think your base problem is the assumption that DateTime d = new DateTime(year, 1, 1); is in the first week of the year, but it could belong to week 52/53 of the previous year.

You will find a solution here.

Henk Holterman
Thanks. Nice that you pointed out to me what I was doing wrong aswell :)
Oskar Kjellin
BTW some pointers on the code. Why use Debug.Assert(>= 1) and not throw an exception? In my opinion that would be a good place for an argument exception
Oskar Kjellin
@Oskar: Assert does throw an exception. But you're right, in production code I would throw a 'normal' exception.
Henk Holterman
Exactly because if you compile for release then all Debug.Assert will go away. :/
Oskar Kjellin
+1  A: 

This should do it:

public static DateTime GetDateFromWeek(int year, int week)
{
    GregorianCalendar calendar = new GregorianCalendar(GregorianCalendarTypes.MiddleEastFrench);
    DateTime d = new DateTime(year, 12, 31);
    int weeksInYear = calendar.GetWeekOfYear(d, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
    int weeksToSubtract = weeksInYear - week;
    d = calendar.AddWeeks(d, -weeksToSubtract);
    d = d.AddDays(1 - (int)d.DayOfWeek);
    return d;
}
Mikael Svenson
This works well but I like that Henk Holterman's solution is a bit more generic. +1 tho for providing a solution
Oskar Kjellin
Both solutions do more or less the same, except mine started at the end of the year instead of at the beginning. Glad you got it working.
Mikael Svenson
Yeah, made some unit tests and they returned the same so. He was a bit faster than you aswell ;)
Oskar Kjellin