简体   繁体   中英

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? I am using 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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