Reputation: 739
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.
Thanks.
Upvotes: 4
Views: 29427
Reputation: 2372
I've just had a related problem in ASP.NET. Issue was occurring on ONE web site on a web server running TWO (almost identical) copies of the code. Had me going for a while, as no logic seemed to fit the symptoms. It turned out to be an issue with the Web.Config. The failing site was missing:
<globalization uiCulture="en" culture="en-AU" /> from the <system.web> section.
Thought I'd just mention this in case it helps anyone.
Upvotes: 0
Reputation: 121
This is happening because the default culture of the machine says that the date format is "dd/MM/yyyy" and in your case, the month is going in as "31" which is incorrect that is why it throws error.
Please set the culture prior to parsing the datetime.
use this code before your code:
CultureInfo CultureInfo1 = (CultureInfo)CultureInfo.CurrentCulture.Clone();
CultureInfo1.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
Thread.CurrentThread.CurrentCulture = CultureInfo1;
let me know if this helps.
Upvotes: 0
Reputation: 44605
Edit:
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;
Upvotes: 4
Reputation: 11760
The problem is that in several countries the month and the day part of the date are turned. In US it is "MM/dd/yyyy", in e.g. germany it is "dd/mm/yyyy".
So you have to specify what format your string is in (in your case it looks like the US format so I choosed this culture):
DateTime date = Convert.ToDateTime(dr["business_dt"], new CultureInfo("en-US"));
dr["StartDate"] = date.ToString("MM/dd/yyyy");
Upvotes: 3