简体   繁体   English

格式异常-字符串未被识别为有效的DateTime

[英]Format Exception - string not recognized as a valid DateTime

I have an issue similar to this > Format exception String was not recognized as a valid DateTime 我有一个与此类似的问题> 格式异常字符串未被识别为有效的DateTime

However, my spec requires a date format of ddMMyyyy, therefore I have modified my code but I am still getting the same error 但是,我的规范要求日期格式为ddMMyyyy,因此我修改了代码,但仍然遇到相同的错误

 DateTime now = DateTime.Now;
 DateTime dt = DateTime.ParseExact(now.ToString(), @"ddMMyyyy", CultureInfo.InvariantCulture);

I am unclear why. 我不清楚为什么。

For ParseExact to work, the string coming in must match exactly the pattern matching. 为了使ParseExact正常工作,输入的字符串必须与模式匹配完全匹配。 In the other question you mentioned, the text was coming from a web form where the format was specified to be exactly one format. 在您提到的另一个问题中,文本来自Web表单,其中该格式被指定为恰好是一种格式。

In your case you generated the date using DateTime.Now.ToString() which will not be in the format ddMMyyyy . 在您的情况下,您使用DateTime.Now.ToString()生成了日期,该日期的格式将不是ddMMyyyy If you want to make the date round trip, you need to specify the format both places: 如果要进行日期往返,则需要在两个地方指定格式:

DateTime now = DateTime.Now;
DateTime dt = DateTime.ParseExact(now.ToString("ddMMyyyy"), @"ddMMyyyy", CultureInfo.InvariantCulture);

Debug your code and look at what the result of now.ToString() is, it's is not in the format of "ddMMyyyy", which is why the parse is failing. 调试您的代码,看看now.ToString()的结果是什么,它的格式不是“ ddMMyyyy”,这就是解析失败的原因。 If you want to output now as a string in the ddMMyyy format, then try now.ToSTring("ddMMyyyy") instead. 如果要now以ddMMyyy格式输出为字符串,请立即尝试。改为使用ToSTring(“ ddMMyyyyy”)。

now.ToString() does not return a string formatted in that way. now.ToString()不返回以这种方式设置格式的字符串。 Try using now.ToString("ddMMyyyy"). 尝试使用now.ToString(“ ddMMyyyy”)。 You might be better off testing with a static string like "30041999" 使用“ 30041999”之类的静态字符串进行测试可能会更好

You code fails because you are attempting to parse a date in the format ddMMyyyy , when by default DateTime.ToString() will produce a format with both date and time in the current culture. 您的代码失败,因为您尝试解析ddMMyyyy格式的日期,默认情况下, DateTime.ToString()将在当前区域性中生成同时包含日期和时间的格式。 For myself in Australia that would be dd/MM/yyy hh:mm:ss p eg 11/10/2013 11:07:03 AM 对于我自己在澳大利亚的那将是dd/MM/yyy hh:mm:ss p例如11/10/2013 11:07:03 AM

You must realise is that the DateTime object actually stores a date as individual components (eg day, month, year) that only needs to be format when you output the value into whatever format you desire. 您必须意识到,DateTime对象实际上将日期存储为单独的组成部分(例如,日,月,年),仅在将值输出为所需的任何格式时才需要设置格式。 Eg 例如

DateTime now = DateTime.Now;
string formattedDate = now.ToString("ddMMyyyy", DateTimeFormatInfo.InvariantInfo);

For more information see the api doc: http://msdn.microsoft.com/en-us/library/8tfzyc64.aspx 有关更多信息,请参见api文档: http : //msdn.microsoft.com/zh-cn/library/8tfzyc64.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM