C # to implement a function that calculates the day of the week according to the month

Source: Internet
Author: User
Tags datetime implement
Function

Sometimes, you would want to calculate the day of the week in ASP.net based on a date. The following code can perform this calculation.
(There are a lot of sample code on the Internet, but I see a lot of it is wrong.) and have been reproduced to reprint, spread open. I'm here to correct it. Oh. )

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+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 Button1_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, do not need too many explanations, a look at the understanding. If applied to reality, it is best to check the textbox for validity, to prevent the importation of illegal data, or to change the textbox to DropDownList. Some people may ask, C # is there a corresponding function? Of course it is. DayOfWeek is the function that returns the day of the week. Now that you've written it here, give me a sample code. As follows:

System.DateTime newdate=new DateTime (2005,1,11);
Response.Write (Newdate.dayofweek);

Other explanation: The algorithm that calculates the day of the week also has Caille formula, there are some formulas that improve on the basis of Kimlarsson formula and Caille formula and so on.



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.