I have a form with two DateTimePicker controls
DateTime.Compare should return 0 if they have the same value, but it thinks they are not the same:
?DateTime.Compare(DatePicker.dtpFrom.Value, DatePicker.dtpTo.Value)
1
?datepicker.dtpFrom.Value
#9/20/2012 7:00:46 PM#
?DatePicker.dtpTo.Value
#9/20/2012 7:00:46 PM#
Am I somehow not thinking clearly? Surely this isn’t some bug in the .NET Framework.
UPDATE
OK I checked the millisecond values and they are off (very slightly). Quirky! I guess it has to do with some subtle delay when the controls are constructed and their default values are set.
?DatePicker.dtpTo.value.ToString("fff")
"616"
?datepicker.dtpFrom.Value.ToString("fff")
"619"
I only care about the date portion, so I solved it:
If DateTime.Compare(DatePicker.dtpFrom.Value.Date, DatePicker.dtpTo.Value.Date) > 0 Then
MsgBox("From_Date cannot be after To_Date", MsgBoxStyle.OkOnly, "Data validation error")
Be careful when comparing multiple DateTimePicker controls. Small differences in the millisecond portion of their values can cause unexpected comparison results, even when no user has edited their default values.
For example, say you have two DateTimePicker controls on your form: FromDate and ToDate, used to establish a date range for a report.
As the question above shows, comparing the two values to ensure that the FromDate is not greater than the ToDate, can result in unexpected results.
If you only care about the Date portion of these controls, you can drop the time value when doing the comparison by reading the Date property on the Value property.