Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

datetime

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.

like image 701
Loris Avatar asked Mar 18 '09 17:03

Loris


2 Answers

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.

like image 146
John Rasch Avatar answered Oct 16 '22 13:10

John Rasch


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

like image 43
Loris Avatar answered Oct 16 '22 11:10

Loris