Hi,
i need to convert date format 1/16/2010 10:10:2011 AM to 16/1/2010 10:10:2011 AM after that i need to put values to database too as datetime datatype.

error I am getting :
"The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. The statement has been terminated. "

string dd = "dd/MM/yyyy";
 string ti = "HH:mm:ss tt";

        string d = DateTime.Now.ToString(dd);
        string mints = DateTime.Now.ToString(ti);
        string result = d+""+mints;
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "insert into tablename Values(7,5,'"+result+"')";
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();

Recommended Answers

All 4 Replies

Date that you want to insert in SQL Server database must be in format MM/dd/yyyy, and time must be in format hh:mm:ss. Don't forget to set data type of collumn in database to datetime.

string dateAndTime = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss");

...
command.ExecuteNonQuery();

Date that you want to insert in SQL Server database must be in format MM/dd/yyyy, and time must be in format hh:mm:ss. Don't forget to set data type of collumn in database to datetime.

string dateAndTime = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss");

...
command.ExecuteNonQuery();

Hi,

many thanks for the reply

but my issue is server time is in UK standard , it giving date value as "MM/dd/yyyy hh:mm.ss tt" format. i saved this value into string.and converted it to "dd/MM/yyyy hh:mm.ss tt" format.then i cant convert this string value back to datetime datatype. Is there any way to parse string to datetime.

Sql Server keeps date in MM/dd/yyyy format. I also had a problem because in Serbia format is: dd.MM.yyyy hh:mm:ss. But following code solve it.

public DateTime convertToUkStandar(string date) 
{
    DateTime dateVariable = Convert.ToDateTime(date);

    return dateVariable.ToString("dd/MM/yyyy hh:mm:ss tt");
}

Thanks jugosoft


it helped

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.