DateTime.MinValue and SqlDateTime overflow

前端 未结 10 528
北恋
北恋 2021-02-01 00:44

I don\'t want to validate txtBirthDate so I want to pass DateTime.MinValue in database.

My code:

 if (txtBirthDate.Text == st         


        
相关标签:
10条回答
  • 2021-02-01 01:16

    Well... its quite simple to get a SQL min date

    DateTime sqlMinDateAsNetDateTime = System.Data.SqlTypes.SqlDateTime.MinValue.Value;
    
    0 讨论(0)
  • 2021-02-01 01:16

    Here is what you can do. Though there are lot many ways to achieve it.

    DateTime? d = null;    
    if (txtBirthDate.Text == string.Empty)
        objinfo.BirthDate = d;
    else
        objinfo.BirthDate =  DateTime.Parse(txtBirthDate.Text);
    

    Note: This will work only if your database datetime column is Allow Null. Else you can define a standard minimum value for DateTime d.

    0 讨论(0)
  • 2021-02-01 01:18

    I am using this function to tryparse

    public static bool TryParseSqlDateTime(string someval, DateTimeFormatInfo dateTimeFormats, out DateTime tryDate)
        {
            bool valid = false;
            tryDate = (DateTime)System.Data.SqlTypes.SqlDateTime.MinValue;
            System.Data.SqlTypes.SqlDateTime sdt;
            if (DateTime.TryParse(someval, dateTimeFormats, DateTimeStyles.None, out tryDate))
            {
                try
                {
                    sdt = new System.Data.SqlTypes.SqlDateTime(tryDate);
                    valid = true;
                }
                catch (System.Data.SqlTypes.SqlTypeException ex)
                {
    
                }
            }
    
            return valid;
        }
    
    0 讨论(0)
  • 2021-02-01 01:20

    use extensions

    public static class DateTimeExtensions
    {
        public static DateTime MinValue(this DateTime sqlDateTime)
        {
            return new DateTime(1900, 01, 01, 00, 00, 00);
        }
    }
    
    
    DateTime date = DateTime.Now;
    Console.WriteLine("Minvalue is {0} ", date.MinValue().ToShortDateString());
    
    0 讨论(0)
提交回复
热议问题