2016-01-24 79 views
2

我正在使用C#,並試圖找出給定的日期和月份是否對閏年有效。這是我的代碼:如何驗證閏年的DateTime

static void Main(string[] args) 
    { 
     Console.WriteLine("The following program is to find whether the Date and Month is Valid for an LEAP YEAR"); 
     Console.WriteLine("Enter the Date"); 
     int date = Convert.ToInt16(Console.ReadLine()); //User values for date and month 
     Console.WriteLine("Enter the Month"); 
     int month = Convert.ToInt16(Console.ReadLine()); 
     { 
      if (month == 2 && date < 30)     //Determination of month and date of leap year using If-Else 
       Console.WriteLine("Your input is valid"); 
      else if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && date < 32) 
       Console.WriteLine("Your inpput valid1"); 
      else if ((month == 4 || month == 6 || month == 9 || month == 11) && date < 31) 
       Console.WriteLine("Your inpput valid2"); 
      else 
       Console.WriteLine("Your input INvalid"); 

      Console.ReadKey(); 
     } 
    }    
    } 
} 

我的問題是,我可以用DateTime這個程序或者這是一個更好的辦法?歡迎任何建議。

回答

3

我建議將輸入作爲string,然後使用DateTime.TryParse方法。 DateTime.TryParse接受stringout DateTimeout keyword),並返回true如果字符串輸入已被正確解析並且是有效的DateTimefalse否則。

從文檔:

如果s是一個閏日的閏年字符串表示當前日曆,該方法解析成功秒。如果s是當前文化當前日曆中非閏年的閏日的字符串表示形式,則解析操作將失敗,並且該方法返回false。

用例:

Console.WriteLine("Please enter a date."); 

string dateString = Console.ReadLine(); 
DateTime dateValue; 

if (DateTime.TryParse(dateString, out dateValue)) 
{ 
    // Hooray, your input was recognized as having a valid date format, 
    // and is a valid date! dateValue now contains the parsed date 
    // as a DateTime. 
    Console.WriteLine("You have entered a valid date!"); 
} 
else 
{ 
    // Aww, the date was invalid. 
    Console.WriteLine("The provided date could not be parsed."); 
} 
+0

我可以按照上述方式查看月份嗎? – vikram

+0

是的,這將檢查整個日期。例如,用戶可能輸入1/23/2016或1-23-2016。 「TryParse」方法甚至可以識別2016年1月23日或2016年1月23日星期六等輸入內容。 – johnnyRose

1

使用已知的閏年的年份部分如2000並追加月份和日期和年份以形成像mm-dd-2000這樣的字符串,其中mmdd是用戶輸入的值。然後使用DateTime.TryParse方法,如果日期有效,則返回true。

2

你可以使用DateTime.DaysInMonth與上年作爲已知閏年像2016年

if (month >= 1 && month <= 12 && date >= 1 && date <= DateTime.DaysInMonth(2016, month)) 
    Console.WriteLine("Your input is valid"); 
else 
    Console.WriteLine("Your input is invalid"); 
0

如果你從單獨的部分工作,然後只是:如果你喜歡

try 
{ 
    new DateTime(year, month, day); 
} 
catch (ArgumentOutOfRangeException) 
{ 
    // it's not valid 
} 

雖然不要依賴例外,然後用juharr的回答,使用DateTime.DaysInMonth