SqlTypeException: SqlDateTime overflow

By FoxLearn 1/21/2025 7:35:18 AM   23
The System.Data.SqlTypes.SqlTypeException: ‘SqlDateTime overflow.' error occurs when you try to insert a DateTime value that is outside the valid range for SQL Server's datetime data type.

The SQL datetime data type supports dates between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM. If you try to insert a DateTime value outside of this range, you'll encounter this exception.

For example, if you attempt to insert a DateTime.MinValue (which is 1/1/0001 12:00:00 AM) into a datetime column, you'll get this exception:

using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString))
{
    using(SqlCommand cmd = new SqlCommand(@"INSERT INTO Events (EventName, EventDate) VALUES (@EventName, @EventDate)", con))
    {
        cmd.Parameters.AddWithValue("@EventName", "Test Event");
        cmd.Parameters.AddWithValue("@EventDate", DateTime.MinValue); // This is outside the valid range for SQL Server datetime

        con.Open();

        cmd.ExecuteNonQuery();
    }
}

In this example, DateTime.MinValue is 1/1/0001 12:00:00 AM, which is below the allowed minimum (1/1/1753 12:00:00 AM) for SQL Server's datetime type, leading to the SqlDateTime overflow error.

To solve this issue, you can use System.Data.SqlTypes.SqlDateTime.MinValue, which corresponds to the minimum valid date (1/1/1753 12:00:00 AM) for SQL Server’s datetime type:

using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString))
{
    using(SqlCommand cmd = new SqlCommand(@"INSERT INTO Events (EventName, EventDate) VALUES (@EventName, @EventDate)", con))
    {
        cmd.Parameters.AddWithValue("@EventName", "Test Event");
        cmd.Parameters.AddWithValue("@EventDate", System.Data.SqlTypes.SqlDateTime.MinValue); // Use SqlDateTime.MinValue for valid date range

        con.Open();

        cmd.ExecuteNonQuery();
    }
}

In this solution, using SqlDateTime.MinValue ensures the date is within the valid range for SQL Server's datetime data type.

Alternatively, you can use System.Data.SqlTypes.SqlDateTime to specify a valid date explicitly:

cmd.Parameters.AddWithValue("@EventDate", new System.Data.SqlTypes.SqlDateTime(1753, 1, 1)); // Valid SQL datetime range

Make sure your SQL table's column is of type datetime to accept this value. If needed, you can also switch to the datetime2 type in SQL Server for a broader date range if that suits your use case.