Error converting dd/MM/yyyy to sql server format

A

Assimalyst

Hi,

I am trying to convert a UK formated date in a textbox to sql server
format. dd/MM/yyyy -> yyyyMMdd.

Here's the code:

IFormatProvider format = new System.Globalization.CultureInfo("en-GB",
true);
DateTime dateUK = DateTime.ParseExact(DOBTxtBx.Text, "dd/MM/yyyy",
format);
string dateSQL = dateUK.ToString("yyyyMMdd");

// Insert data to dataset table row
patientRow["pntDOB"] = dateSQL;

If, for instance DOBTxtBx.Text = 21/09/1909

Stepping through with debugger gives:
dateUK = 9/21/1909 (this does not seem to be correct, it's MM/dd/yyyy
???)
dateSQL = 19090921 (this does seem OK!)

But the program then errors on patientRow["pntDOB"] = dateSQL; saying
'String was not recognised as a valid DateTime'.

Any ideas what the problem is?

Many Thanks
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

Do not use string , use a DateTime:

IFormatProvider format = new System.Globalization.CultureInfo("en-GB",
true);
DateTime dateUK = DateTime.ParseExact(DOBTxtBx.Text, "dd/MM/yyyy", format);


// Insert data to dataset table row
patientRow["pntDOB"] = dateUK;


Just make sure that pntDOB is of type DateTime
 
G

Guest

Do not use string , use a DateTime:
IFormatProvider format = new System.Globalization.CultureInfo("en-GB",
true);
DateTime dateUK = DateTime.ParseExact(DOBTxtBx.Text, "dd/MM/yyyy", format);

That assumes you can be sure the user entered the value in the correct format.

If you're using WinForms it's better to use a DateTimePicker.

Otherwise you should require the value be in an ISO 8601 compliant format.
(And use a regular expression to validate it before accepting it?)
 
J

John B

Assimalyst said:
Hi,

I am trying to convert a UK formated date in a textbox to sql server
format. dd/MM/yyyy -> yyyyMMdd.

Here's the code:

IFormatProvider format = new System.Globalization.CultureInfo("en-GB",
true);
DateTime dateUK = DateTime.ParseExact(DOBTxtBx.Text, "dd/MM/yyyy",
format);
string dateSQL = dateUK.ToString("yyyyMMdd");

// Insert data to dataset table row
patientRow["pntDOB"] = dateSQL;

If, for instance DOBTxtBx.Text = 21/09/1909

Stepping through with debugger gives:
dateUK = 9/21/1909 (this does not seem to be correct, it's MM/dd/yyyy
???)
dateSQL = 19090921 (this does seem OK!)

But the program then errors on patientRow["pntDOB"] = dateSQL; saying
'String was not recognised as a valid DateTime'.

Any ideas what the problem is?

Many Thanks
Try formatting it as the iso standard which is YYYY-MM-DD and
YYYY-MM-DDTHH:mm:ss.
Or as others have said, use the intrinsic type instead of a conversion.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top