tags:

views:

1166

answers:

7

As the title says, given the year and the week number, how do I get the month number?

edit: if a week crosses two months, I want the month the first day of the week is in.

edit(2): This is how I get the week number:

CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay, DayOfWeek.Monday);

I'm just trying to do the reverse.

+2  A: 

Wouldn't it also depend on the day of the week?

Ed Guiness
+1  A: 

You cant. You need at least the day on which the 1st week starts (or when the week starts), to get an accurate answer.

leppie
Which is defined in CultureInfo
Henk Holterman
A: 

You cant. A week may start in one month and end in another.

Chathuranga Chandrasekara
A: 

I think you're assuming that a "week" is any group of 7 sequential days. It isn't. Given Year(2008), Week(5), you could be in either January or Febuary, depending on when your "week" starts.

Jim H.
+1  A: 

Another problem you could face is that most years do not start at the beginning of a week, which shifts everything.

Perchik
+8  A: 

If you assume that the first day of your definition of week is the same day as the 1st day of the year, then this will work:

int year = 2000;
int week = 9;
int month = new DateTime(year, 1, 1).AddDays(7 * (week - 1)).Month;

Obviously, a true answer would depend on how you define the first day of the week, and how you define how a week falls into a month when it overlaps more than one.

John Rasch
Clever answer...
Chuck Conway
A: 

This is what I ended up doing:

static int GetMonth(int Year, int Week)
{
    DateTime tDt = new DateTime(Year, 1, 1);

    tDt.AddDays((Week - 1) * 7);

    for (int i = 0; i <= 365; ++i)
    {
        int tWeek = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(
            tDt, 
            CalendarWeekRule.FirstDay, 
            DayOfWeek.Monday);
        if (tWeek == Week)
            return tDt.Month;

        tDt = tDt.AddDays(1);
    }
    return 0;
}

I would have preferred something simpler, but it works :)

Loris