How do I get date form week, working also with 53-week years? c#

Posted by Oskar Kjellin on Stack Overflow See other posts from Stack Overflow or by Oskar Kjellin
Published on 2010-03-29T10:36:09Z Indexed on 2010/03/29 10:43 UTC
Read the original article Hit count: 432

Filed under:
|
|
|

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;
    }

© Stack Overflow or respective owner

Related posts about c#

Related posts about date