ASP.NET  

How to Fix the Varchar to Datetime Conversion Error in ASP.NET

In this article, we will explore a common issue that developers encounter when working with ASP.NET applications that interact with SQL Server: the "The conversion of a varchar data type to a datetime data type resulted in an out-of-range value" error. We will discuss why it happens, how to fix it temporarily, and the best long-term solution.

Introduction

When an ASP.NET application inserts data into a SQL Server database, it often needs to handle date and time values. One common issue arises when trying to pass a DateTime value as a string, which SQL Server cannot correctly interpret due to regional date formatting differences. This issue leads to the "out-of-range" error, typically when trying to insert DateTime.Now as a string into the database.

In this article, we will discuss the problem in detail, walk through a temporary fix, and then introduce the best solution: parameterized queries. This approach not only resolves the error but also improves the security and maintainability of your code.

The Problem: DateTime Formatting Issues

When data is inserted into a SQL Server database, especially DateTime values, SQL Server expects these values to be in a specific format. If the DateTime value is passed as a string in an unexpected format, SQL Server may fail to parse it correctly, resulting in an out-of-range error.

Here’s an example scenario:

In an ASP.NET application, the code might dynamically build a SQL query to insert data into the ContactInfo table, which includes a DateTime field:

str1 = "insert into ContactInfo(FirstName, LastName, MobileNo, Email, Country, State, City, APIType, AppName, Reason, ReasonComment, Message, CompanyName, ContactPerson, usertype, indCompanyName, date)";

str1 += " values('-', '-', '" + Contact1.Text + "', '" +
        Email.Text.Replace(" ", "") + "', '" +
        drpCountry.SelectedItem.Text + "', '" +
        state + "', '" +
        city + "', '" +
        Assestlist + "', '" +
        SiteName.Text.Replace("'", "_") + "', '" +
        drpApi.SelectedValue + "', '" +
        usercomment.Replace("'", "_") + "', '" +
        txtMessage.Text.Replace("'", "_") + "', '" +
        Fname.Text.Replace(" ", "") + "', '" +
        Lname.Text.Replace(" ", "") + "', '" +
        usertype + "', '" +
        infocompany.Text + "', '" +
        DateTime.Now + "')";

In this code, DateTime.Now is concatenated directly into the SQL query. When DateTime.Now is converted to a string, it might be formatted in a way that SQL Server cannot interpret correctly, such as:

13-01-2026 10:25:40

SQL Server may expect the DateTime to be in an ISO-compliant format like:

2026-01-13 10:25:40

If the format does not match, SQL Server may throw the out-of-range error.

Temporary Fix: Use ISO 8601 Format

The quickest way to fix this issue is to format the DateTime value as an ISO-compliant string before passing it to SQL Server. This ensures that SQL Server always understands the date format, regardless of the regional settings on the server.

Modify the code like this:

string sqlDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

str1 += " values('-', '-', '" + Contact1.Text + "', '" +
        Email.Text.Replace(" ", "") + "', '" +
        drpCountry.SelectedItem.Text + "', '" +
        state + "', '" +
        city + "', '" +
        Assestlist + "', '" +
        SiteName.Text.Replace("'", "_") + "', '" +
        drpApi.SelectedValue + "', '" +
        usercomment.Replace("'", "_") + "', '" +
        txtMessage.Text.Replace("'", "_") + "', '" +
        Fname.Text.Replace(" ", "") + "', '" +
        Lname.Text.Replace(" ", "") + "', '" +
        usertype + "', '" +
        infocompany.Text + "', '" +
        sqlDate + "')";

By using DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), the date is formatted in a universally accepted ISO 8601 format, which SQL Server will always understand. While this works as a temporary fix, it’s not the most robust or maintainable solution.

The Long-Term Solution: Use Parameterized Queries

Although formatting the DateTime value as a string resolves the issue temporarily, the best solution is to use parameterized queries. Parameterized queries not only eliminate date conversion issues but also improve security and prevent SQL injection attacks.

Here’s how to refactor the code to use parameterized queries:

string query = @"insert into ContactInfo
(FirstName, LastName, MobileNo, Email, Country, State, City,
 APIType, AppName, Reason, ReasonComment, Message,
 CompanyName, ContactPerson, usertype, indCompanyName, date)
values
('-', '-', @MobileNo, @Email, @Country, @State, @City,
 @APIType, @AppName, @Reason, @ReasonComment, @Message,
 @CompanyName, @ContactPerson, @usertype, @indCompanyName, @date)";

Now, create the parameters:

SqlParameter[] param =
{
    new SqlParameter("@MobileNo", Contact1.Text),
    new SqlParameter("@Email", Email.Text.Replace(" ", "")),
    new SqlParameter("@Country", drpCountry.SelectedItem.Text),
    new SqlParameter("@State", state),
    new SqlParameter("@City", city),
    new SqlParameter("@APIType", Assestlist),
    new SqlParameter("@AppName", SiteName.Text),
    new SqlParameter("@Reason", drpApi.SelectedValue),
    new SqlParameter("@ReasonComment", usercomment),
    new SqlParameter("@Message", txtMessage.Text),
    new SqlParameter("@CompanyName", Fname.Text),
    new SqlParameter("@ContactPerson", Lname.Text),
    new SqlParameter("@usertype", usertype),
    new SqlParameter("@indCompanyName", infocompany.Text),
    new SqlParameter("@date", SqlDbType.DateTime) { Value = DateTime.Now }
};

SqlHelper.ExecuteNonQuery(SQL, CommandType.Text, query, param);

Explanation of Parameterized Queries

  • Avoids String Concatenation: Using parameters means we no longer have to manually concatenate user inputs or DateTime values into the query string. This approach helps prevent errors and SQL injection attacks.

  • SQL Parameters: We pass the DateTime.Now value as a parameter with the correct type (SqlDbType.DateTime). SQL Server handles the conversion, ensuring it is always in the correct format.

  • Prevents SQL Injection: By using parameters, we avoid manually building the query string, which protects the application from SQL injection attacks.

Conclusion

The "The conversion of a varchar data type to a datetime data type resulted in an out-of-range value" error occurs when SQL Server attempts to convert a string (often from DateTime.Now) into a DateTime value, and the format is not understood. The most straightforward fix is to format the date as an ISO-compliant string. However, the best practice is to use parameterized queries, which not only resolve the issue but also enhance security, maintainability, and performance.

summary

  1. Temporary fix: Format DateTime as yyyy-MM-dd HH:mm:ss.

  2. Long-term solution: Use parameterized queries to prevent errors and SQL injection.

This approach ensures that your application works reliably across different environments and is easier to maintain in the long run.