SoFunction
Updated on 2025-03-06

C# method to calculate the day of the week based on the Kim Larson algorithm

This article describes the method of C# calculating the day of the week based on the Kim Larson algorithm. Share it for your reference. The specific analysis 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 the date, m represents the number of months, and y represents the number of years.

Note: There is a difference in the formula from other formulas:
Consider January and February as the thirteenth and fourteenth months of the previous year. For example: if it is 2004-1-10, it will be converted into: 2003-13-10 to substitute the formula to calculate.

#region Calculate the day of the week based on year, month, day (=CaculateWeekDay(2010,11,29);) /// Calculate the day of the week based on year, month and day (=CaculateWeekDay(2010,11,29);)///Year///moon///day///
public static 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+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;
 }
 #endregion

I hope this article will be helpful to everyone's C# programming.