/// <Summary>
/// Obtain the week number of the year from the specified date
/// </Summary>
/// <Param name = "DT"> specified date </param>
/// <Returns> Number of weeks in a year </returns>
Private Static int datepart (datetime DT)
{
Int weeknow = convert. toint32 (Dt. dayofweek); // today's day of the week
Int daydiff = (-1) * (weeknow + 1); // The day difference between today and last weekend
Int days = system. datetime. Now. adddays (daydiff). dayofyear; // the last day of the year.
Int weeks = days/7;
If (days % 7! = 0)
{
Weeks ++;
}
// At this time, weeks is the week of the current year.
Return (Weeks + 1 );
}
The above function can be obtained, but the processing in the first week is not good. It shows 53 weeks instead of 1 week.
==============================================================
Later, based on my recent ideas, I wrote the following program to solve the problem of poor processing in the first week. Annotations are linked to my ideas and algorithms.
Private Static int getweekofyear ()
{
// 1. Find the last day of the first week (first obtain the day of the week in February, so that the number of weekends in the first week is known)
Int firstweekend = 7-convert.toint32 (datetime. parse (datetime. Today. Year + "-1-1"). dayofweek );
// 2. Obtain the day of the year.
Int currentday = datetime. Today. dayofyear;
// 3. (today minus the weekend of the first week)/7 equals to the number of weeks in the first week plus the number of weeks in the first week. Today is the week of the year.
// The only special case that has been taken into consideration is that today is just in the first week, so from the first week is 0 plus the first week of 1 is still 1
Return convert. toint32 (math. Ceiling (currentday-firstweekend)/7.0) + 1;
}