C# Convert.DateTime 抛出错误:字符串未被识别为“06-13-2012”的有效日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11009655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert.DateTime throws error: String was not recognized as a valid DateTime for "06-13-2012"
提问by petko_stankoski
I am inserting a date into my database, the value which comes from:
我在我的数据库中插入一个日期,其值来自:
s.theDate = Convert.ToDateTime("06-13-2012");
and I get the error, "String was not recognized as a valid DateTime". How do I resolve this?
我收到错误消息,“字符串未被识别为有效的日期时间”。我该如何解决?
采纳答案by Eren Ers?nmez
Try this:
尝试这个:
DateTime.ParseExact("06-13-2012", "MM-dd-yyyy", System.Globalization.CultureInfo.InvariantCulture)
回答by Kishore Kumar
s.theDate = DateTime.ParseExact("06-13-2012", "MM-dd-yyyy", System.Globalization.CultureInfo.InvariantCulture)
回答by ie.
Just use ParseExactas already suggested or populate Convert.ToDateTimewith the second parameter:
只需ParseExact按照已经建议的方式使用或Convert.ToDateTime使用第二个参数填充:
Convert.ToDateTime("06-13-2012", new DateTimeFormatInfo{FullDateTimePattern = "MM-dd-yyyy"});
回答by Eric Smith
Looking at the behaviour of ToStringon a DateTimetype using an InvariantCulture, this:
查看使用 anToString的DateTime类型的行为InvariantCulture,这是:
new DateTime(2012, 6, 13).ToString(CultureInfo.InvariantCulture)
results in:
结果是:
06/13/2012 00:00:00
So, conversely, one can assume that parsing the date with an invariant culture works Ok:
因此,相反,可以假设使用不变文化解析日期可以正常工作:
Convert.ToDateTime("06-13-2012", CultureInfo.InvariantCulture)
... and it does.
......它确实如此。
That being said, assumingdate/time formats is a little dangerous. I'd say you want formats to be culture-specific when the UI is considered. Otherwise, you would want formats to be culture-agnostic. Although Microsoft have adopted MM/dd/yyyy as a culture-agnostic format, it's an ambiguous format which isn't something that I would want to build a large system on.
话虽如此,假设日期/时间格式有点危险。我想说的是,在考虑 UI 时,您希望格式特定于文化。否则,您会希望格式与文化无关。尽管 Microsoft 已采用 MM/dd/yyyy 作为与文化无关的格式,但它是一种模棱两可的格式,我不想在其上构建大型系统。
回答by Marcus
There is a global standard called ISO 8601 that you may (imo should) use. Using this standard, this is what you will end up with.
您可以(imo 应该)使用一个名为 ISO 8601 的全球标准。使用这个标准,这就是你最终的结果。
Convert.ToDateTime("2012-06-03");

