我正在使用C#,我正在尝试查找给定的日期和月份是否对闰年有效。这是我的代码:
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
用于此计划,还是更好的方法?欢迎任何建议。
答案 0 :(得分:3)
我建议将输入作为string
,然后使用DateTime.TryParse
方法。 DateTime.TryParse
接受string
和out DateTime
(out keyword),如果字符串输入都已正确解析且有效true
,则返回DateTime
},和false
否则。
来自文档:
如果s是当前日历中闰年中闰日的字符串表示形式,则该方法成功解析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.");
}
答案 1 :(得分: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");
答案 2 :(得分:1)
使用已知的闰年作为年份部分,例如2000并附加月,日和年以形成类似mm-dd-2000的字符串,其中mm
和dd
是用户输入的值。然后使用DateTime.TryParse方法,如果日期有效,则返回true。
答案 3 :(得分:0)
如果你是从不同的部分工作,那么只需:
try
{
new DateTime(year, month, day);
}
catch (ArgumentOutOfRangeException)
{
// it's not valid
}
虽然如果您不想依赖异常,那么请使用DateTime.DaysInMonth
来回答juharr的回答。