在c#中将对象转换为datetime时出现问题
我在对象中获取字符串值说28/05/2010。虽然我把它转换为DateTime它抛出异常:
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 :
字符串未被识别为有效的DateTime。
String was not recognized as a valid DateTime.
代码是:
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.
您的异常的原因是您为sql服务器和您的应用程序设置了不同的文化。因此,您将数据库中的字符串作为dd / MM / yyyy获取,在应用程序中将此值解析为MM / dd / yyyy。 28是无效的月份,所以它抛出一个例外。使用 DateTime.ParseExact(dateString,dd / MM / yyyy,CultureInfo.InvariantCulture);
获取正确的值,或使用相同的文化。
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.
更新:您可以从控制面板 - >区域和语言检查Windows设置。对于sql服务器文化设置以及如何为您的应用定义文化在这里是一个很好的解释 http://alainrivas.blogspot.com/2008/09/aspnet-and-sql-server-globalization.html
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