C A function that calculates the day of the week based on year month and day

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

DateTime.Now.ToString("dddd",new System.Globalization.CultureInfo("zh-cn"));

Today, I saw some introduction about calculating the day of the week according to the year, month and day implemented by C # on the Internet:

The algorithm is as follows:
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.
The code is as follows:


 //y -in, m -Month, d -Date  

string CaculateWeekDay(int y,int m,int d)
  {
    string[] weekstr ={ " Day ", "1", "2", "3", "4", "5", "6" };

    if (m < 3)
    {
      m += 12;
      if (y % 400 == 0 || y % 100 != 0 && y % 4 == 0)
      {
        d--;
      }
    }
    else
    {
      d += 1;
    }
    return " Week " + weekstr[(d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7]; 
    

  }

Related articles: