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

后端 未结 11 2302
你的背包
你的背包 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:58

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

    0 讨论(0)
  • 2020-12-17 19:01

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

    0 讨论(0)
  • 2020-12-17 19:03
    // Calculate the week number according to ISO 8601
    
        public static int Iso8601WeekNumber(DateTime dt)
        {
                return  CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(dt, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
        }
    
    // ...
    
    DateTime dt = DateTime.Now;
    
    // Calculate the WeekOfMonth according to ISO 8601
    int weekOfMonth = Iso8601WeekNumber(dt) - Iso8601WeekNumber(dt.AddDays(1 - dt.Day)) + 1;
    
    0 讨论(0)
  • 2020-12-17 19:07

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

    0 讨论(0)
  • 2020-12-17 19:08

    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.

    0 讨论(0)
提交回复
热议问题