C Example Code for Calculating Day of the Week by Date

  • 2021-11-02 01:59:31
  • OfStack

This example uses the Kim Larson formula to calculate the day of the week in the future based on the date:

First, look at the definition of Kim Larson's calculation formula in Baidu Encyclopedia:

Kim Larson calculation formula

W= (d+2*m+3* (m+1)/5+y+y/4-y/100+y/400) mod 7

In the formula, d represents the number of days in a date, m represents the number of months, and y represents the number of years.

Note: There is a difference between the formula and other formulas:

January and February are regarded as 103 and 104 months of the previous year. For example, if it is 2004-1-10, it will be converted into 2003-13-10 to be substituted into the formula.

1. Client (called by ajax):


$.get('CaculateWeekDay', { y: 2016, m: 8, d: 9 }, function (result) {
alert(result);
})

2. Server side:


/// <summary>
///  Calculate the day of the week for a specific date 
/// </summary>
/// <param name="y"> Year </param>
/// <param name="m"> Month </param>
/// <param name="d"> Day </param>
/// <returns></returns>
public string CaculateWeekDay(int y, int m, int d) 
{
if (m == 1 || m == 2) 
{
m += 12;
y--;
}
int week = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7;
string weekstr = "";
switch (week)
{
case 0: weekstr = " Week 1"; break;
case 1: weekstr = " Week 2"; break;
case 2: weekstr = " Week 3"; break;
case 3: weekstr = " Week 4"; break;
case 4: weekstr = " Week 5"; break;
case 5: weekstr = " Week 6"; break;
case 6: weekstr = " Week 7"; break;
}
return weekstr;
}

Related articles: