C # obtain the week number of the current year

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.