简体   繁体   English

无法将字符串识别为有效的DateTime格式异常

[英]String was not recognized as a valid DateTime format exception

I am trying to do a simple parsing using following statements: 我正在尝试使用以下语句进行简单的解析:

//In actual code the date time value comes from db
var dateTime = new DateTime(2018, 04, 26);

var dtExtact = DateTime.ParseExact(dateTime.ToString(), "dd MMM yyyy HH:mm:ss:fff",null);

Now when I try doing this getting error, 现在,当我尝试执行此错误操作时,

System.FormatException: 'String was not recognized as a valid DateTime.' System.FormatException:'字符串未被识别为有效的DateTime。

I did have a look at the MSDN sample, but it does not provide any pointers on whats wrong with my date time. 我确实看过MSDN示例,但是它没有提供任何有关我的日期时间出问题的指针。

If you would like to parse a date-time string in a specific format, make sure that your formatted date/time string matches the format of your parser. 如果要解析特定格式的日期时间字符串,请确保格式化的日期/时间字符串与解析器的格式匹配。

In your example "round-tripping" a date/time is easy to achieve by reusing the same format string for formatting the date and for parsing: 在您的示例“往返”中,通过重复使用相同的格式字符串来格式化日期和进行解析,很容易实现日期/时间:

var dateTime = new DateTime(2018, 04, 26);
const string dateFormat = "dd MMM yyyy HH:mm:ss:fff";
var dtExact = DateTime.ParseExact(
    dateTime.ToString(dateFormat)
,   dateFormat
,   null
);
Console.WriteLine("{0} {1}", dateTime, dtExact);

Demo. 演示

Both ToString() and Parse() are designed to automagically extract the Region setting from Windows. ToString()和Parse()均旨在从Windows自动提取Region设置。 It is rarely a good idea to override this behavior. 覆盖此行为很少是一个好主意。 And apparently your pattern is not a valid one. 显然,您的模式不是有效模式。 For all we know, ':' is not actually the proper cultural seperator for Time elements 就我们所知,“:”实际上不是时间元素的正确文化分隔符

Overall this seems rather suspect - you turn a DateTime to string, only to parse it again right there. 总体而言,这似乎令人怀疑-您将DateTime转换为字符串,然后仅在此处再次对其进行解析。 I can only guess it is for testing. 我只能猜测它是用于测试。 But testing for what is the question. 但是测试什么是问题。

I have 3 general rules when dealing with DateTimes: 在处理DateTimes时,我有3条通用规则:

  • Always store, retrieve and transmit the UTC value. 始终存储,检索和传输UTC值。 You do not want ot add timezones to your issues. 您不希望将时区添加到您的问题中。 That way lies madness . 那就是疯狂 There are rare exceptions, but then you are pretty much on your own to deal with that mess 很少有例外,但是那样的话,您几乎可以独自应对
  • Avoid storing, retreival or transmission as Text. 避免以文本形式存储,恢复或传输。 keep it in proper DataTypes as long as possible 尽可能长时间将其保留在适当的DataTypes中
  • If you can follow the 2nd rule (using XML or some other serialsiation), at least pick a fixed Culture Format, Format String and string encoding at all endpoints. 如果可以遵循第二条规则(使用XML或其他一些序列化方法),请至少在所有端点上选择固定的区域性格式,格式字符串和字符串编码。 You do not want to add those issues to your worries 您不想将这些问题添加到您的后顾之忧

Following those rules, I rarely had any issues. 遵循这些规则,我很少遇到任何问题。

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

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