How do I get the month number from the year and week number in c#?

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


this should be able to help

 public int getMonth(int weekNum, int year)
 {
     DateTime Current = new DateTime(year, 1, 1);
     System.DayOfWeek StartDOW = Current.DayOfWeek;
     int DayOfYear = (weekNum * 7) - 6; //1st day of the week

     if (StartDOW != System.DayOfWeek.Sunday) //means that last week of last year's month
     {
         Current = Current.AddDays(7 - (int)Current.DayOfWeek);
     }
     return Current.AddDays(DayOfYear).Month;
}

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.


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 :)

Tags:

C#

Datetime