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")
You want to check the .Net documentation on DateTime.Compare, a value of 1 implies that dtpFrom.Value is greater than dtpTo.
I'd also suggest there's a millisecond or two difference between the dates, since even down to the second they're likely not to be the same.
I'd suggest comparing the .ToString("yyyy MM dd HH:mm:ss") values to get around millisecond differences
UPDATE
Further to the comments, here's a better suggestion for stripping off the milliseconds
dateTime.AddTicks( - (dateTime.Ticks % TimeSpan.TicksPerSecond));
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.
If DateTime.Compare(dtpFrom.Value.Date), DateValue(dtpTo.Value.Date) > 0 Then
{invalid range error message}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With