views:

74

answers:

2

Hi, 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 recognized 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.

+1  A: 

Use DateTime.ParseExact and specify the format string as dd/MM/yyyy.

David M
+1 I think that was the OP's original intention as that line has been commented out, all that is missing really is the format provider.
James
No it is not working
Lalit
Add the revised code and the new error in the question please.
David M
I deleted it. The code is in question as it is.
Lalit
Apologies - I meant the ParseExact method. Answer edited.
David M
+1  A: 

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

Teddy
I think you are right.Ok thanks sir, but how can i set this??
Lalit
how to change culture date formate?
Lalit
see my updated answer.
Teddy
Thanks I tried this , it was working. But To change the server's settings is not the proper way. So I just thought , . I insert in web.config as <globalization culture="en-GB"/> as ur URL sugessted. Thanks once again.
Lalit
I'm glad to help.
Teddy