DateTime.TryParse 将十进制转换为日期时间
下面的代码行返回 true (它不应该)...并将 1.0228 转换为日期时间...
DateTime.TryParse(1.0228,out temporaryDateTimeValue)
请有人帮助我。
The following line of code return true (which it should not)....and convert 1.0228 into datetime...
DateTime.TryParse(1.0228,out temporaryDateTimeValue)
Somebody please help me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这将无法编译。
但是,如果您将其用引号引起来(并稍微清理一下),
那么,是的,您将得到
true
。您需要阅读文档才能理解原因,但基本上,有许多不同的方法来格式化日期,您偶然发现了一种(也许M.yyyy
?)。如果您不希望它解析,我可以建议
那么
success
是false
。我从文档中的评论中注意到:
基本上,
TryParse
非常努力地“尝试”解析您给它的字符串(尽管“Try
”实际上指的是该方法返回一个布尔值来表示成功/失败指示)。This will not compile.
However, if you wrap it in quotes (and clean it up a little bit),
then, yes, you will get
true
back. You need to read the documentation to understand why, but basically, there are many different ways to format dates and you stumbled on one (maybeM.yyyy
?).If you don't want it to parse, may I suggest
Then
success
isfalse
.I note from the remarks in the documentation:
Basically,
TryParse
"tries" very hard to parse the string you give it (although the "Try
" really refers to the fact that the method returns a bool for success/failure indication).不,该代码不会返回 true - 它甚至无法编译:
错误:
如果将其更改为“1.0228”,它确实会返回 true,是的。看起来它使用的是“M.yyyy”格式,这无疑对某些文化有效......并强调了为什么在我看来使用
DateTime.TryParse
是一个坏主意。如果您考虑了特定格式(或一组格式),则应使用DateTime.TryParseExact
代替,以便您可以指定格式。我通常发现指定确切的格式是一个好主意,并且我通常还会指定
CultureInfo.InvariantCulture
除非日期直接来自用户(这种情况很少见,在我的经验)。No, that code doesn't return true - it doesn't even compile:
Error:
If you change it to "1.0228" it does return true, yes. It looks like it's using a format of "M.yyyy", which is no doubt valid for some cultures... and highlights why it's a bad idea to use
DateTime.TryParse
in my view. If you've got a specific format (or set of formats) in mind, you should useDateTime.TryParseExact
instead so you can specify the format.I usually find it's a good idea to specify the exact format, and I usually also specify
CultureInfo.InvariantCulture
unless the date is coming directly from the user (which is rare, in my experience).