C# 日期时间解析问题
我当前的代码如下所示:
DateTime dateBegin = DateTime.ParseExact(begin, "MM/dd/yyyy", null);
DateTime dateEnd = DateTime.ParseExact(end, "MM/dd/yyyy", null);
但是只要“end”中的日期不同,它就会引发异常。我从 DateTimePicker 控件获取日期,因此日期可能看起来像“1/12/2010”,然后它会抛出异常。我该如何避免这种情况?
谢谢。
My current code looks like this:
DateTime dateBegin = DateTime.ParseExact(begin, "MM/dd/yyyy", null);
DateTime dateEnd = DateTime.ParseExact(end, "MM/dd/yyyy", null);
But it throws an exception whenever the date in "end" is different. I get the dates from a DateTimePicker control, thus the date may look like "1/12/2010" and then it'll throw the exception. How do I avoid this?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是winform吗?只需使用
.Value
在选择器上,您将获得正确的DateTime
- 无需解析。最终,“1/12/2010”不是“MM/dd/yyyy”;您也可以尝试“M/d/yyyy”作为后备?
Is this winforms? just use
.Value
on the picker and you'll get the rightDateTime
- no need to parse.Ultimately, "1/12/2010" isn't "MM/dd/yyyy"; you could also try ""M/d/yyyy" as a fallback?
为什么不使用 DateTimePicker.Value?
Why don't you use DateTimePicker.Value?
如果您从 DateTimePicker 获取值,为什么不使用该控件已经是 DateTime 的值?我不确定你为什么要尝试解析该字符串......
If you are getting the value from a DateTimePicker, why not use tha Value of that control which is already a DateTime? I'm not sure why you're trying to parse the string...
如果您提供了堆栈/异常信息 ti 可能更容易提供帮助,但我希望它会抛出,因为 ParseExact 失败可能是因为它不适合您也试图缩小范围的格式
If you provided the stack/exception information ti may be easier to help but I would expect it is throwing as the ParseExact is failing probably because it doesn't fit the format you are trying to narrow it too
这个怎么样?
一个很好的参考是
http://msdn.microsoft.com/en-us/库/8kb3ddd4.aspx
how about this ?
A good reference is
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx