Able
Able

Reputation: 3912

Datetime parsing throw Format Exception error

when I changed the system date format as dd/mm/yyyy, the web application throwing the format error, the error attached here,

enter image description here

if the system have default date format, its working fine. I tried to format the string as well, but its too not worked. Please help me to correct the issue.

EDITED

Here is the code raising the exception

cmd.Parameters.Add("@createdon", SqlDbType.DateTime).Value = DateTime.Parse(createdon);

Upvotes: 0

Views: 1230

Answers (2)

Able
Able

Reputation: 3912

Solved the issue by correcting the code as,

cmd.Parameters.Add("@createdon", SqlDbType.DateTime).Value = DateTime.ParseExact(createdon, "MM/dd/yyyy", CultureInfo.InvariantCulture);

so its working any system Datetime settings, thank you all.

Upvotes: 0

richardtallent
richardtallent

Reputation: 35363

When using DateTime.Parse(), if you want it to parse dates using a format other than the culture the program is running under, you need to specify an IFormatProvider as the second argument to specify which incoming date format you are expecting.

Example:

cmd.Parameters.Add("@createdon", SqlDbType.DateTime).Value
   = DateTime.Parse(createdon, new CultureInfo("en-US", true));

This will parse dates in dd/MM/yyyy format, the default format for the US.

Upvotes: 1

Related Questions