2013-09-03 1 views
0

대신 사용 :년 및 월 번호가있는 달의 일을 계산 하시겠습니까?

int noOfDaysInMonth = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month); 

내가 한 달에 일의 수를 얻기 위해 전달 된이 개 값을 사용하려면 :

public ActionResult Index(int? month, int? year) 
{ 
    DateTime Month = System.Convert.ToDateTime(month); 
    DateTime Year = System.Convert.ToDateTime(year); 
    int noOfDaysInMonth = DateTime.DaysInMonth(Year, Month); 

(년, 월) 잘못된 인수하지 않다고 생각된다? 어떤 아이디어? 어쩌면 system.conert.todatetime.month?

답변

3

그들은 DateTime 변수이지만 intDaysInMonth 필요 :

int noOfDaysInMonth = DateTime.DaysInMonth(year.Value, month.Value); 

가 널이 될 수있는 경우 :

int noOfDaysInMonth = -1; 
if(year != null && month != null) 
    noOfDaysInMonth = DateTime.DaysInMonth(year.Value, month.Value); 
+0

null 인 경우 어떻게해야합니까? – Renan

+0

@Renan : edited. –

1

두 개의 DateTime 인스턴스를 사용하는 DateTime.DaysInMonth 메서드에 과부하가 없습니다. 두 개의 DateTime 인스턴스를 만드는 대신 직접받은 매개 변수를 DaysInMonth으로 전달하십시오.

메쏘드 은 null 값을 취할 수 없으므로 nullables를 삭제하거나 입력 내용을 살균합니다. 즉, 년과 월이 null인지 확인하고, 그렇다면 일부 기본값을 사용하십시오.

0

DateTime.DaysInMonth가 INT 매개 변수가 아닌 날짜 시간 매개 변수

public static int DaysInMonth(
    int year, 
    int month 
) 
걸립니다

하지만 조심하십시오. nullable int를 전달하고 있습니다. 그래서 그들은 현재 어떤 DateTime 객체를 사용할 필요가 없습니다 값

if(month.HasValue && year.HasValue) 
{ 
    var numOfDays = DaysInMonth(year.Value, month.Value); 
} 
0

이 경우 전에 확인,하지만 당신은 필요 입력의 유효성을 검사!

public ActionResult Index(int? month, int? year) 
{ 
    int noOfDaysInMonth = -1; 

    if(year.HasValue && year.Value > 0 && 
      month.HasValue && month.Value > 0 && month.Value <=12) 
    { 
     noOfDaysInMonth = DateTime.DaysInMonth(year.Value, month.Value); 
    } 
    else 
    { 
     // parameters weren't there or they had wrong values 
     // i.e. month = 15 or year = -5 ... nope! 

     noOfDaysInMonth = -1; // not as redundant as it seems... 
    } 

    // rest of code. 
} 

if 작품을 왼쪽에서 오른쪽으로 조건을 평가하기 때문이다.