Reputation: 21
I am trying to compare to compare to String values.
Dim tod As String = "04/02/2016_01:20"
Dim DBookTo As String = "08/02/2014_01:30"
If tod = DBookTo
'do something
If tod<DBookTo
'do something
If tod>DBookTo
'dosomething
endif
Ideally I want here the 3rd condition to be executed because "08/02/2014_01:30" is smaller than "04/02/2016_01:20". But the 2nd condition is being executed. Please help me here.
Upvotes: 0
Views: 78
Reputation: 11
It looks like you want to compare dates. So instead of strings, you can use date variables.
ex:
Dim dt1 as Date=#15/2/2014 8:00:00#
Dim dt2 as Date=#14/3/2012 6:00:00#
if dt1>dt2
'when dt1 comes later in the calender than dt2 (which is the case here)
elseIf dt1<dt2
'when dt1 comes before dt2
else
'when both are same
end if
Upvotes: 0
Reputation: 125660
That's because you're performing string comparison, what means your input is compared char by char, until first difference is found.
First difference is on second character, between 4
and 8
. And because 4
is lower then 8
that's makes tod
lower then DBookTo
.
To make it work and really compare the values, not string representation you have to use proper type, which in your case is DateTime
:
Dim tod As DateTime = New DateTime(2016, 2, 4, 1, 20, 0)
Dim DBookTo As DateTime = New DateTime(2014, 2, 8, 1, 30, 0)
You can also get DateTime
instance from your string using DateTime.ParseExact
method:
Dim todString As String = "04/02/2016_01:20"
Dim DBookToString As String = "08/02/2014_01:30"
Dim tod As DateTime = DateTime.ParseExact(todString, "MM/dd/yyyy_hh:mm", System.Globalization.DateTimeFormatInfo.InvariantInfo)
Dim DBookTo As DateTime = DateTime.ParseExact(DBookToString, "MM/dd/yyyy_hh:mm", System.Globalization.DateTimeFormatInfo.InvariantInfo)
Upvotes: 2