A small example of C's function for calculating the day of the week based on the day month and year
- 2020-05-17 06:14:43
- OfStack
The algorithm is as follows:
Kim larsen formula
W= (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400) mod 7
In the formula, d refers to the number of days in a date, m to the number of months, and y to the number of years.
Note: there is one difference between the formula and other formulas:
Take January and February as the 103 months and 104 months of the previous year. For example, if it is 2004-1-10, it can be converted into: 2003-13-10 to substitute into the formula.
The code is as follows:
Call method:
Kim larsen formula
W= (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400) mod 7
In the formula, d refers to the number of days in a date, m to the number of months, and y to the number of years.
Note: there is one difference between the formula and other formulas:
Take January and February as the 103 months and 104 months of the previous year. For example, if it is 2004-1-10, it can be converted into: 2003-13-10 to substitute into the formula.
The code is as follows:
//y - years, m - month, d The date -
string CaculateWeekDay(int y,int m, int d)
{
if(m==1) m=13;
if(m==2) m=14;
int week=(d+2*m+3*(m+1)/5+y+y/4-y/100+y/400)%7;
string weekstr="";
switch(week)
{
case 1: weekstr=" week 1"; break;
case 2: weekstr=" week 2"; break;
case 3: weekstr=" week 3"; break;
case 4: weekstr=" week 4"; break;
case 5: weekstr=" week 5"; break;
case 6: weekstr=" week 6"; break;
case 7: weekstr=" Sunday "; break;
}
return weekstr;
}
Call method:
Label1.Text=CaculateWeekDay(2004,12,9);