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

送分小仙女□ 提交于 2019-12-25 05:38:08

问题


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?


回答1:


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



回答2:


Leap year validation

static void Main(string[] args)
{
 try
 {
  Console.Write("Please Enter the Year: ");
  int year = int.Parse(Console.ReadLine());
  if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))
      {
        Console.WriteLine("The year {0}, is a Leap Year", year);
       }
      else
       {
        Console.WriteLine("The year {0}, is not a Leap Year", year);
      }
  }
    catch (Exception ex)
{
  Console.WriteLine(ex.Message);
}
  Console.ReadLine(); 
}

or simply you can use

if (DateTime.IsLeapYear(year))
     {
         //your logic
     }
 else
    {
    }



回答3:


If you have three integers years, months and days, first check that years is between 1 and 9999, then check that months is between 1 and 12, and finally check that days is between 1 and DateTime.DaysInMonth(years, months).

Addition: If it's for database storage, depending on the specific SQL column type, the range of valid years might be narrower, e.g. 1753 through 9999. Anyway, the so-called "proleptic" Gregorian calendar is not historical correct, it's a kind of "extrapolation".




回答4:


Setting the value for February month with 28 or 29 depending on if that year is a leap year or not.

if (currentDate.Month == 2 && DateTime.IsLeapYear(currentDate.Year))
{
     //your logic to work on february month
}
else
{

}


来源:https://stackoverflow.com/questions/17121329/validating-date-leap-year-or-not-before-inserting-into-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!