2012-02-20 1 views
1

안녕하세요 저는 c#을 처음 사용하고 프로그래밍하는 것은 일반적으로 다른 사람들의 코드를 수정하는 방법을 배우려 고 노력하고 있습니다. 아래 코드를 수정하면 금액을 계산하고 싶습니다. 1 월에 작업 일수가 남아 있지만 문제는 코드가 월의 일 단위로 실행되므로 이번 달에 29 일이지만 코드로 인한 코드 오류는 으로 실행됩니다. 나는 어떤 부분 어떤 도움을 변경할 수있는 코드의 것 큰 일C# 월에 남은 근무일을 계산하는 방법

private void days() 
    { 

     //Monday to Friday are business days. 
     var weekends = new DayOfWeek[] { DayOfWeek.Saturday, DayOfWeek.Sunday }; 
     DateTime testing = DateTime.Now; 



     string month1 = testing.ToString("M "); 
     string year1 = testing.ToString("yyyy"); 
     int month = Convert.ToInt32(month1); 
     int year = Convert.ToInt32(year1); 


     //Fetch the amount of days in your given month. 
     int daysInMonth = DateTime.DaysInMonth(year, month); 
     string daysleft = testing.ToString("d "); 
     int daystoday = Convert.ToInt32(daysleft); 

     //Here we create an enumerable from 1 to daysInMonth, 
     //and ask whether the DateTime object we create belongs to a weekend day, 
     //if it doesn't, add it to our IEnumerable<int> collection of days. 
     IEnumerable<int> businessDaysInMonth = Enumerable.Range(daystoday, daysInMonth) 
               .Where(d => !weekends.Contains(new DateTime(year, month, d).DayOfWeek)); 

     //Pretty smooth. 

     int count = 0; 
     foreach (var day in businessDaysInMonth) 
     { 
      count = count + 1; 
     } 
     textBox9.Text = count.ToString(); 


    } 
} 

답변

9
public static IEnumerable<int> Range(int start, int count) 

두 번째 매개 변수는 끝이 아니라 카운트라는 것을 알 수 있습니다.

당신이 원하는 카운트는 아마도 :

private static readonly DayOfWeek[] weekends = new DayOfWeek[] { DayOfWeek.Saturday, DayOfWeek.Sunday }; 

bool IsWorkDay(DateTime day)//Encapsulate in a function, to simplify dealing with holydays 
{ 
    return !weekends.Contains(day.DayOfWeek); 
} 

int WorkDaysLeftInMonth(DateTime currentDate) 
{ 
    var remainingDates = Enumerable.Range(currentDate.Day,DateTime.DaysInMonth(currentDate.Year,currentDate.Month)-currentDate.Day+1) 
         .Select(day=>new DateTime(currentDate.Year, currentDate.Month, day)); 
    return remainingDates.Count(IsWorkDay); 
} 
4

문자열로 날짜를 변환 한 후 다시 정수 값으로 구성 요소를 분석 할 필요가 없습니다 :로 daysInMonth - daystoday + 1

난 당신의 코드를 다시 작성할 것 . DateTime "테스트"의 '월', '일'및 '연도'속성을 확인하십시오.

은 (CodeInChaos 당신의 대답을 가지고 있지만이 크게 코드를 단순화 재미있는 사실이다.)

구현할 필요가 없습니다
0
private int GetWorkingDaysLeftInMonth() 
    { 
     // get the daysInMonth 
     int daysInMonth = GetDaysInMonth(); 

     // locals 
     int businessDaysInMonth = 0; 
     int day = DateTime.Now.Day; 
     bool isWeekDay = false; 

     int currentDay = (int) DateTime.Now.DayOfWeek; 
     DayOfWeek dayOfWeek = (DayOfWeek)currentDay; 

     // iterate the days in month 
     for (int x = day; x < daysInMonth; x++) 
     { 
      // increment the current day 
      currentDay++; 

      // if the day is greater than 7 
      if (currentDay > 7) 
      { 
       // reset the currentDay 
       currentDay = 1; 
      } 

      // get the dayOfWeek 
      dayOfWeek = (DayOfWeek) currentDay; 

      switch(dayOfWeek) 
      { 
       case DayOfWeek.Monday: 
       case DayOfWeek.Tuesday: 
       case DayOfWeek.Wednesday: 
       case DayOfWeek.Thursday: 
       case DayOfWeek.Friday: 

        // is a week day 
        isWeekDay = true; 

        // required 
        break; 

       default: 

        // is a NOT week day 
        isWeekDay = true; 

        // required 
        break; 
      } 

      if (isWeekDay) 
      { 
       // increment the value 
       businessDaysInMonth++; 
      } 
     } 

     // return value 
     return businessDaysInMonth; 
    } 

    private int GetDaysInMonth() 
    { 
     // initial value 
     int daysInMonth = 0; 

     switch(DateTime.Now.Month) 
     { 
      case 1: 
      case 3: 
      case 5: 
      case 7: 
      case 8: 
      case 10: 
      case 12: 

       daysInMonth = 31; 

       // required; 
       break; 

      case 2: 

       daysInMonth = 28; 

       // to do (leap year) 
       bool isLeapYear = IsLeapYear(); 

       // if isLeapYear 
       if (isLeapYear) 
       { 
        // set to 29 
        daysInMonth = 29; 
       } 

       // required 
       break; 

      case 4: 
      case 6: 
      case 9: 
      case 11: 

       daysInMonth = 30; 

       // required; 
       break; 
     } 

     // return value 
     return daysInMonth; 
    } 

    private bool IsLeapYear() 
    { 
     // initial value 
     bool isLeapYear = false; 

     int year = DateTime.Now.Year; 

     //determine the year 
     switch(year) 
     { 
      case 2012: 
      case 2016: 
      case 2020: 
      // to do: Go as far out as you need to 

       // set to true 
       isLeapYear = true; 

       // required 
       break; 
     } 

     // return value 
     return isLeapYear; 
    } 
+0

가'자신을 GetDaysInMonth'. 프레임 워크는 이미'DateTime.DaysInMonth'을 포함하고 있습니다. 윤년 논리는 추악합니다 (프레임 워크 코드를 다시 복제합니다). 모듈러스 연산자를 사용하여 임의의 연도에 대한 도약을 계산할 수 있습니다. – CodesInChaos

+0

나는 그것을하기위한 가장 효율적인 방법이 아니라 그것을하는 방법을 표현하기 위해 5 분 안에 그것을 썼다. – user1054326

관련 문제