[英]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);
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条通用规则:
Following those rules, I rarely had any issues. 遵循这些规则,我很少遇到任何问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.