2

我正在使用 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这个程序还是更好的方法?欢迎任何建议。

4

4 回答 4

3

我建议将输入作为 a string,然后使用该DateTime.TryParse方法。DateTime.TryParse接受 astringout DateTime( out 关键字),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.");
}
于 2016-01-24T03:01:22.200 回答
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");
于 2016-01-24T03:59:12.617 回答
1

对年份部分使用已知的闰年,例如 2000 年,并附加月份、日期和年份以形成一个字符串,如 mm-dd-2000用户输入的值在哪里mm和是。dd然后使用DateTime.TryParse方法,如果日期有效则返回 true。

于 2016-01-24T03:06:31.043 回答
1

如果您从不同的部分工作,那么只需:

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

尽管如果您不想依赖异常,那么请使用 juharr 的答案,使用DateTime.DaysInMonth.

于 2016-02-13T01:45:38.327 回答