I am getting string value in object let say "28/05/2010". While i am converting it in to DateTime it is throwing exception as :
String was not recognize开发者_JAVA百科d as a valid DateTime.
The Code is:
object obj = ((Excel.Range)worksheet.Cells[iRowindex, colIndex_q17]).Value2;
Type type = obj.GetType();
string strDate3 = string.Empty;
double dbl = 0.0;
if (type == typeof(System.Double))
{
dbl = Convert.ToDouble(((Excel.Range)worksheet.Cells[iRowindex, colIndex_q17]).Value2);
strDate3 = DateTime.FromOADate(dbl).ToShortDateString();
}
else
{
DateTime dt = new DateTime().Date;
//////////dt = DateTime.Parse(Convert.ToString(obj));
**dt = Convert.ToDateTime(obj).Date;**
strDate3 = dt.ToShortDateString();
}
The double star "**" line gets exception.
The reason for your exception is that you have different culture set up for sql server and your application. So, you are getting the string from the database as "dd/MM/yyyy" and in your application this value is parsed as "MM/dd/yyyy". The 28 is invalid month, so it throws an exception. Use DateTime.ParseExact(dateString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
to get the right value, or use the same culture.
UPDATE: You can check windows settings from Control Panel -> Region and Language. For the sql server culture settings and how you can define culture for your application here is a good explanation http://alainrivas.blogspot.com/2008/09/aspnet-and-sql-server-globalization.html
Use DateTime.ParseExact
and specify the format string as dd/MM/yyyy.
精彩评论