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

后端 未结 11 2359
你的背包
你的背包 2020-12-17 18:40

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

11条回答
  •  没有蜡笔的小新
    2020-12-17 18:48

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

提交回复
热议问题