c#生日月份限制

时间:2018-02-20 03:24:05

标签: c#

我不是C#专家,所以在我问这个问题时请记住这一点: 在我的C#中,我有一个表单项目,用户输入他们出生的年份,月份和日期,并告诉他们他们的生日所在的星期几。 我想确保用户没有输入不存在的日期示例: 2018年2月30日。 所以,我想创建一个弹出消息,说明"日期不存在"为此,我创建了这段代码:

static string FindDay(int year, int month, int day)
{
    //The reason why we are using a new keyword is because i belive: we are creating a new object and to do that you must use a new keyword.
    //DateTime is its own data type like int or string.
    DateTime birthdayDate = new DateTime(year, month, day);

    string dayOfWeek = birthdayDate.DayOfWeek.ToString(); //Don't confuse the local dayOfWeek varible with the DayOfWeek property
    return dayOfWeek;
}

private void FindButton_Click(object sender, EventArgs e)
{
    //The reason(I think) that we are casting to int data types is because its a "DateTime" data type.
    int year = (int)numericYear.Value;
    int month = (int)numericMonth.Value;
    int day = (int)numericDay.Value;
    //Date checking to maek sure date isn't invaild.

    int maxDays = DateTime.DaysInMonth(year, month);
    if (day > maxDays)
    {
        MessageBox.Show("Invaild date");

    }

    string dayString = FindDay(year, month, day);
    MessageBox.Show("You were born on a:" + dayString);
}

但是当我在程序中运行时,一切运行正常并弹出消息,然后在消息后我看到: ERROR:

System.ArgumentOutOfRangeException: 'Year, Month, and Day parameters describe an un-representable DateTime.'

它弹出

string dayOfWeek = birthdayDate.DayOfWeek.ToString();

我该如何解决这个问题?为什么会这样?

2 个答案:

答案 0 :(得分:2)

int maxDays = DateTime.DaysInMonth( year, month );  // set a breakpoint here, and see what happens
if ( day > maxDays )
{
    MessageBox.Show("Invaild date");
}
else
{
    string dayString = FindDay(year, month, day);
    MessageBox.Show("You were born on a:" + dayString);
} 

答案 1 :(得分:0)

如果您不必显示消息来解释日期无效的原因,则可以将其TryParseExact简单地插入DateTime中。 无需转换为int,只需查看每月的天数即可。

var inputs = new List<inputDate>
{
    new inputDate(1,1,2018),
    new inputDate(32,1,2018),
    new inputDate(1,13,2018),
    new inputDate(1,1,-2018)
};

foreach (var input in inputs)
{
    GetDayOfBirth(input);
}


private void GetDayOfBirth(inputDate input)
{
    CultureInfo invC = CultureInfo.InvariantCulture;
    if (DateTime.TryParseExact(
            $"{input.D}/{input.M}/{input.Y}",
            $"d/M/yyyy",
            invC,
            DateTimeStyles.None,
            out DateTime birthday)
        )
    {
        Console.WriteLine("You were born on a:" + birthday.DayOfWeek);
        return;
    }
    Console.WriteLine("Invalid date");
}