You need to get the number of the week. From the first week of the year everything is clear. And if the first week will be the current one (26.03 - 01.04) taking into account the leap year. Those. was the previous week (03/19 - 03/25) 52?

    2 answers 2

    You can count the week in different ways. It can be considered the first week in which the first of January. It can be considered the first week in which the first Monday of the year. It can be considered the first week, most of which belongs to the new year. How exactly to consider - to choose you. In .NET, the enumeration of System.Globalization.CalendarWeekRule is responsible for this choice.

    You can get the week number by date as follows:

     var dt = new DateTime(2017, 1, 1); var cal = new GregorianCalendar(); var weekNumber = cal.GetWeekOfYear(dt, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday); // получается 52 

    We see that according to the rule “the year starts with a full week” on January 1, 2017 belongs to the 52nd week of the past, 2016.

    • but 2019 shows as a leap year with 53 weeks. - Just_Deniss
    • @Just_Deniss: How is that? Show your code what it gives out (and why leap of 2019 follows from this). - VladD
    • private void numericUpDown1_ValueChanged (object sender, EventArgs e) {var dt = new DateTime (Convert.ToInt32 (numericUpDown1.Value), 1, 1); var cal = new GregorianCalendar (); var weekNumber = cal.GetWeekOfYear (dt, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday); label1.Text = weekNumber.ToString (); } 2018, 2024, 2029 ... shows only 1 week, 2019, 2025, 2030 shows 53 - Just_Deniss
    • @Just_Deniss: Well, yes, that’s right, that’s right. - VladD

    I do not know if I understood correctly what you want to do, but let's say:

    You have a DateTime object. I do not know how you get it, whether it is DateTime.Now , DateTime.UtcNow , or something else. The task is to determine which week is on the account for this date.

    Then the task becomes trivial:

     DateTime myDateTime = DateTime.Now; int firstDayOfYear = (int)new DateTime(myDateTime.Year, 1, 1).DayOfWeek; int weekNumber = (myDateTime.DayOfYear + firstDayOfYear) / 7; 

    Then the weekNumber variable will store the value, and the first week will be 0 , the second will be 0 , and so 1 . If you want to count weeks starting from 1 , then just

     int weekNumber = (myDateTime.DayOfYear + firstDayOfYear) / 7 + 1; 

    Something like this.

    • No not like this. Is your week starting any day? - Igor
    • @Igor Well, the specifics in the question was also not much, but yes, I will now correct it - selya
    • and what specifics do you miss? Can it be worth checking with the author? - tym32167
    • @Igor behold, it seems so - selya
    • @ tym32167 well, the period is 19.03 - 25.03 - a week from Mon to Sun, so I think the joint was still mine. I corrected, so true, it seems - selya