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 开发者_StackOverflow社区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
You are forgetting about the time portion of the DateTime. You should use this instead:
if (dateTimePicker1.Value < DateTime.Today)
toolStripStatusLabel1.Text = "Date Selected is not Proper";
else (dateTimePicker1.Value >= DateTime.Today)
toolStripStatusLabel1.Text = "Date Selected is " + dateTimePicker.Value;
Because DateTime.Now includes the time of the day, try DateTime.Today this only gets the date.
because of the DateTime.Now
not only returning the data, it also returns the time. so to fix that:
use DateTime.Now.Date
instead of DateTime.Now
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
, or DateTime.Today
for this kind of comparisons.
The DateTimePicker has a MinimumDate property that will do this checking for you -- have you tried that? Here is the documentation:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.mindate(v=vs.80).aspx
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
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.
精彩评论