user74042 user74042 - 1 month ago 4
C# Question

Error when parsing datetime

I get the following error message in my C# program in the statement:

dr["StartDate"] = Convert.ToDateTime(dr["business_dt"]).ToString("MM/dd/yyyy");

I do not get this error on my US machine.But it throws an error on the user's machine located outside the US.
The dateformat being returned from datareader is: 08/31/2010 12:00:00 AM

System.FormatException: String was not recognized as a valid DateTime.
at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi,
DateTimeStyles styles) at System.Convert.ToDateTime(String value,
IFormatProvider provider) at
System.String.System.IConvertible.ToDateTime(IFormatProvider provider)
at System.Convert.ToDateTime(Object value)

Please advise.




use DateTime.ParseExact method:

var dateString = dr["business_dt"].ToString();
var format = "MM/dd/yyyy hh:mm:ss tt";
var dateTime = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
dr["StartDate"] = dateTime;