C # calculates the day of the week based on the year, month, and day.

Source: Internet
Author: User

Sometimes, you may want to calculate the day of the week based on a certain date in ASP. NET. The followingCodeThis computation can be performed.
(There are a lot of sample code on the Internet, but I have read a lot and it is wrong. They were all reproduced and circulated. I am here to make corrections. Haha .)

String caculateweekday (INT y, int M, int D)
{
If (M = 1) {M = 13; y --;}
If (M = 2) {M = 14; y --;}
Int week = (D + 2 * m + 3 * (m + 1)/5 + Y/4-y/100 + Y/400) % 7 + 1;
String weekstr = "";
Switch (week)
{
Case 1: weekstr = "Monday"; break;
Case 2: weekstr = "Tuesday"; break;
Case 3: weekstr = "Wednesday"; break;
Case 4: weekstr = "Thursday"; break;
Case 5: weekstr = "Friday"; break;
Case 6: weekstr = "Saturday"; break;
Case 7: weekstr = "Sunday"; break;
}

Return weekstr;
}
Private void button#click (Object sender, system. eventargs E)
{
Int year = int. parse (textbox1.text );
Int month = int. parse (textbox2.text );
Int day = int. parse (textbox3.text );
Label1.text = caculateweekday (year, month, day );
}

The code is very simple and does not require much explanation. You can understand it at a glance. If it is applied to reality, it is best to check the validity of textbox to prevent illegal data input; or change textbox to dropdownlist. Someone may ask, is there a function in C? Of course. Dayofweek is the function that returns the day of the week. Now that we have written it here, let's give a sample code. As follows:

System. datetime newdate = new datetime (November 1, 11 );
Response. Write (newdate. dayofweek );

Other Instructions: Calculate the day of the weekAlgorithmThere are also the cailer formula, and some improved formulas based on the kempilsen formula and the cailer formula.

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.