Mark
Mark

Reputation: 2760

DateTime error in C#

When I enter the date in the below format then my db accepts it

22/06/2011 00:00:00

But when I enter the date in this format

mm/dd/yyyy 00:00:00

then my DB throws an error saying DateTime not recognised. My calendar gives me DateTime in mm/dd/yyyy hh:mm:ss format. How can I change that in my code to dd/mm/yyyy?

   DateTime Res_date = Convert.ToDateTime(txt_DT.Text);

        param[5] = new MySqlParameter("@RespondBy", MySqlDbType.DateTime);
        param[5].Value = Res_date;
        command.Parameters.AddWithValue("@RespondBy", Res_date);

The DateTime is entered in the txt_DT.text textbox.

How can I convert the date and then convert the string to DateTime?

Upvotes: 0

Views: 1543

Answers (1)

Erik Philips
Erik Philips

Reputation: 54636

I think you should use the DateTime.ParseExact method. Msdn Documentation http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

DateTime Res_date = DateTime.ParseExact(txt_DT.Text, "MM/dd/yy hh:mm:ss", ... );

Then you can use String.Format to convert your DateTime to any format you want.

http://www.csharp-examples.net/string-format-datetime/

Upvotes: 3

Related Questions