解析日期时间时出错
我在 C# 程序中的语句中收到以下错误消息:
dr["StartDate"] = Convert.ToDateTime(dr["business_dt"]).ToString("MM/dd/yyyy");
我在美国计算机上没有收到此错误。但它会在位于美国境外的用户计算机上引发错误。 从 datareader 返回的日期格式为: 08/31/2010 12:00:00 AM
System.FormatException:字符串未被识别为有效的日期时间。 在 System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles 样式)位于 System.Convert.ToDateTime(字符串值, IFormatProvider 提供者)位于 System.String.System.IConvertible.ToDateTime(IFormatProvider 提供程序) 在 System.Convert.ToDateTime(对象值)
请告知。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
编辑:
使用
DateTime.ParseExact
方法:Edit:
use
DateTime.ParseExact
method:问题在于,在一些国家/地区,日期的月份和日期部分会翻转。在美国,它是“MM/dd/yyyy”,在德国,它是“dd/mm/yyyy”。
因此,您必须指定字符串的格式(在您的情况下,它看起来像美国格式,所以我选择了这种区域性):
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):
发生这种情况是因为机器的默认区域性表示日期格式为“dd/MM/yyyy”,而在您的情况下,月份为“31”,这是不正确的,这就是它引发错误的原因。
请在解析日期时间之前设置区域性。
在您的代码之前使用此代码:
让我知道这是否有帮助。
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:
let me know if this helps.
我刚刚在 ASP.NET 中遇到了一个相关问题。问题发生在运行两份(几乎相同)代码副本的 Web 服务器上的一个网站上。让我走了一段时间,因为似乎没有逻辑符合这些症状。原来是Web.Config 的问题。失败的网站丢失了:
我想我只是提一下这一点,以防它对任何人有帮助。
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:
Thought I'd just mention this in case it helps anyone.