SoFunction
Updated on 2025-03-07

C# How to get the time difference between two times and remove the weekend (take the working day)

This article example describes how C# obtains the time difference between two times and removes the weekend. Share it for your reference. The specific analysis is as follows:

Generally speaking, there are many codes that can only take the time difference between working days, but there are very few codes that can only take the time difference between working days. This code implements this function.

protected void Page_Load(object sender, EventArgs e)
{
 DateTime start = ("2012-12-10");
 DateTime end= ("2012-12-18");
 TimeSpan span = end - start;
 //int totleDay=;
 //DateTime spanNu = (span);
 int AllDays=Convert.ToInt32()+1;//All days of the gap int totleWeek = AllDays / 7;//How many weeks does the difference int yuDay = AllDays % 7; //Except for the number of days in the whole week int lastDay = 0;
 if (yuDay == 0) //It's exactly the whole week {
  lastDay = AllDays - (totleWeek * 2);
 }
 else
 {
  int weekDay = 0;
  int endWeekDay = 0; //How many days are there on Saturday or Sunday?  switch ()
  {
  case :
   weekDay = 1;
   break;
  case :
   weekDay = 2;
   break;
  case :
   weekDay = 3;
   break;
  case :
   weekDay = 4;
   break;
  case :
   weekDay = 5;
   break;
  case :
   weekDay = 6;
   break;
  case :
   weekDay = 7;
   break;
  }
  if ((weekDay == 6 && yuDay >= 2) || (weekDay == 7 && yuDay >= 1) || (weekDay == 5 && yuDay >= 3) || (weekDay == 4 && yuDay >= 4) || (weekDay == 3 && yuDay >= 5) || (weekDay == 2 && yuDay >= 6) || (weekDay == 1 && yuDay >=7))
  {
  endWeekDay =2;
  }
  if ((weekDay == 6 && yuDay < 1) || (weekDay == 7 && yuDay <5) || (weekDay == 5 && yuDay < 2) || (weekDay == 4 && yuDay < 3) || (weekDay == 3 && yuDay < 4) || (weekDay == 2 && yuDay < 5) || (weekDay == 1 && yuDay < 6))  {
  endWeekDay = 1;
  }
  lastDay = AllDays - (totleWeek * 2) - endWeekDay;
 }
  = ();
}

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