【问题标题】:Validating Date (Leap year or not) before inserting into Database在插入数据库之前验证日期(是否闰年)
【发布时间】:2013-06-15 07:40:23
【问题描述】:

当我需要将日期插入数据库时​​,我需要检查两件事:

  1. 如果选择第 31 天,则本月有 31 天
  2. 如果选择了 2 月,我需要检查是否是闰年,以防用户选择 29

目前我正在使用一个填充有if'selse's 的长函数进行检查。

C# 中是否有任何方法可以在我插入日期之前检查它是否有效?

【问题讨论】:

    标签: c# database validation date leap-year


    【解决方案1】:
    DateTime temp;
    if (DateTime.TryParse(yourString, out temp))
    {
        //valid, use temp to insert into DB.
    }
    else
    {
        //not valid.
    }
    

    【讨论】:

      【解决方案2】:

      闰年验证

      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(); 
      }
      

      或者干脆你可以使用

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

      【讨论】:

      【解决方案3】:

      如果您有三个整数yearsmonthsdays,首先检查years 是否在19999 之间,然后检查months 是否在1 和@987654330 之间@,最后检查days1DateTime.DaysInMonth(years, months)之间。

      补充:如果是用于数据库存储,根据具体的SQL列类型,有效年份的范围可能会更窄,例如: 17539999。反正所谓的“预知”公历是不符合历史正确性的,是一种“外推”。

      【讨论】:

        【解决方案4】:

        根据该年是否为闰年,将二月的值设置为 28 或 29。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-06-14
          • 2015-07-24
          • 1970-01-01
          • 1970-01-01
          • 2023-03-25
          • 2022-01-25
          • 1970-01-01
          • 2015-10-25
          相关资源
          最近更新 更多