【发布时间】:2015-06-29 14:58:49
【问题描述】:
我正在尝试验证用户可以提供的日期时间格式。这是示例代码...
DateTime tempDateTime;
string _userFormat = "aa";
string tempDateTime2 = DateTime.Now.ToString(_userFormat);
bool b = DateTime.TryParseExact(tempDateTime2, _userFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out tempDateTime);
Console.WriteLine("{0},{1}", tempDateTime, b);
Console.ReadLine();
这将返回 true(b 的值)和有效的 dateTime (tempDateTime)。我的印象是这将返回 false,因为 _userFormat 不是有效格式。那么有没有其他方法或者我错过了什么。
谢谢
【问题讨论】:
-
是什么让您认为
aa不是有效的格式字符串?它不传达任何信息,但实际上并不是无效的。您总是可以检查重新解析的值是否与原始值有任何关系......您需要决定需要保留多少信息 - 年/月/日?时间到分钟?到第二个? -
如果您在调试器中查看
tempDateTime2的值,您就会明白为什么它会成功。 -
@DStanley:是的 - 我在一分钟前相应地编辑了我的评论:)
-
请注意,即使是“有效”格式字符串也可能会丢失原始数据/时间中的信息 - 您可以使用仅提取日期、时间、小时、年份等的“有效”字符串。
标签: c# .net visual-studio-2010