简体   繁体   English

AC#函数检查日期,年份,月份中的日期

[英]A C# function to check a date from day month year

I have three strings/ints which are day, month, and year. 我有三个字符串/整数,分别是日,月和年。 Is there any way of checking if they're in a valid DateTime format? 有什么方法可以检查它们是否为有效的DateTime格式? I am using ASP.NET. 我正在使用ASP.NET。

When a user registers, he enters a month, day and year. 用户注册时,他输入月,日和年。

I used to convert the three variables to a string and tryParse to check if it's legal, but the only problem is running the same project on a different machine because some different machines use different date formats. 我曾经将这三个变量转换为字符串,然后使用tryParse来检查其合法性,但是唯一的问题是在不同的计算机上运行同一项目,因为某些不同的计算机使用不同的日期格式。

how about this: 这个怎么样:

    private bool IsValidDate(int year, int month, int day)
    {
        if (year < DateTime.MinValue.Year || year > DateTime.MaxValue.Year)
            return false;

        if (month < 1 || month > 12)
            return false;

        return day > 0 && day <= DateTime.DaysInMonth(year, month);
    }

If you already have day , month and year as three separate ints, you can use directly one of DateTime's constructors , instead of putting them into a string and re-parsing it as a DateTime. 如果您已经将daymonthyear作为三个独立的int,则可以直接使用DateTime的构造函数之一 ,而不用将它们放入字符串并将其重新解析为DateTime。

DateTime mydate;
myDate = new DateTime(year, month, day);

this will throw a ArgumentOutOfRangeException if the date is invalid, so you should wrap this in a try/catch block and use a catch(ArgumentOutOfRangeException e) block to manage the logic when your date does not have a valid format. 如果日期无效,则将引发ArgumentOutOfRangeException ,因此,当日期格式无效时,应将其包装在try / catch块中,并使用catch(ArgumentOutOfRangeException e)块来管理逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM