Search code examples
c#databasevalidationdateleap-year

Validating Date (Leap year or not) before inserting into Database


When I need to insert date into the database I need to check 2 things:

  1. If this month has 31 days in case day 31 was selected
  2. If February is selected, I need to check if it's a leap year in case the user selected 29

Currently I'm checking this using a long function filled with if's and else's.

Is there any method in C# that can check a date if it's valid or not before I insert it?


Solution

  • DateTime temp;
    if (DateTime.TryParse(yourString, out temp))
    {
        //valid, use temp to insert into DB.
    }
    else
    {
        //not valid.
    }