我正在使用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
這個程序或者這是一個更好的辦法?歡迎任何建議。
我可以按照上述方式查看月份嗎? – vikram
是的,這將檢查整個日期。例如,用戶可能輸入1/23/2016或1-23-2016。 「TryParse」方法甚至可以識別2016年1月23日或2016年1月23日星期六等輸入內容。 – johnnyRose