从 datTimePicker 中选择日期
这是一个代码片段,其中我必须选择正确的日期来预订约会,它应该进行简单的验证,以确保为约会选择的日期是当前日期或晚于该日期的日期。
if (dateTimePicker1.Value < DateTime.Now)
toolStripStatusLabel1.Text = "Date Selected is not Proper";
else (dateTimePicker1.Value >= DateTime.Now)
toolStripStatusLabel1.Text = "Date Selected is " + dateTimePicker.Value;
但是,在这里,当我选择当前日期时,它总是进入 if 块。每当我选择晚于当前日期的日期时,它都会正常工作。
谢谢
Here is a code snippet where in I have to select a proper date to book an appointment, it should do a simple validation that the date selected for the appointment is a date which is either the current date or later than that.
if (dateTimePicker1.Value < DateTime.Now)
toolStripStatusLabel1.Text = "Date Selected is not Proper";
else (dateTimePicker1.Value >= DateTime.Now)
toolStripStatusLabel1.Text = "Date Selected is " + dateTimePicker.Value;
However, here when I select the Current date it always goes in the if block.When ever I select a date later than the current date it works fine.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您忘记了日期时间的时间部分。你应该使用这个:
You are forgetting about the time portion of the DateTime. You should use this instead:
由于 DateTime.Now 包含一天中的时间,因此请尝试 DateTime.Today 这仅获取日期。
Because DateTime.Now includes the time of the day, try DateTime.Today this only gets the date.
因为
DateTime.Now
不仅返回数据,还返回时间。所以要解决这个问题:使用
DateTime.Now.Date
而不是DateTime.Now
because of the
DateTime.Now
not only returning the data, it also returns the time. so to fix that:use
DateTime.Now.Date
instead ofDateTime.Now
DateTime.Now 包括两者日期和时间,以及
'2011-07-29' 始终小于 '2011-07-29 13:50:00'
为此使用
DateTime.Now.Date
或DateTime.Today
种比较。DateTime.Now includes both the date and the time, and
'2011-07-29' is always less than '2011-07-29 13:50:00'
Use
DateTime.Now.Date
, orDateTime.Today
for this kind of comparisons.DateTimePicker 有一个 MaximumDate 属性,可以为您执行此检查 - 您尝试过吗?这是文档:
另外,请记住 DateTime.Now 有小时/分钟/秒 - 从您的示例中不清楚您是否只想比较 DateTime 的日期部分...?
希望这有帮助,
约翰
The DateTimePicker has a MinimumDate property that will do this checking for you -- have you tried that? Here is the documentation:
Also, keep in mind that DateTime.Now has hours/minutes/seconds - it's not clear from your example if you want to compare just the date portion of the DateTime...?
Hope this helps,
John
这是由于毫秒差异造成的。您只需要检查日期部分而不是时间部分...尝试使用仅包含日期的
TimeSpan
这应该可以解决您的问题。that is due to the milisecond difference.. you need to check only the date part not the time part... try using a
TimeSpan
with only date in it this should solve your problem.