Problem when comparing two DateTime variables

  • Thread starter Thread starter Mika M
  • Start date Start date
M

Mika M

I need to compare two DateTime variables named as t1 and t2 using VB.NET
2003. If t1 is any earlier time as t2, only then program should do
something like...

If (t1 < t2) Then
'DoSomethingHere...
End If

But I don't figue out how comparing DateTimes is working.

I tried to compare these variables with same time in Immediate-window...

?t1
#3/30/2005 10:18:14 AM#
?t2
#3/30/2005 10:18:14 AM#
?DateTime.Compare(t1, t2)
1
?DateTime.Compare(t2, t1)
-1
?t1.CompareTo(t2)
1
?t1 = t2
False
?t1.Equals(t2)
False

....so why these t1 ja t2 variables content is not same in this case
according comparing results !?!
 
Mika,

I find the most easy one to compare the ticks

if t1.Ticks < t2.Ticks then

(the bracket is not needed in VBNet)

I hope this helps,

Cor
 
I find the most easy one to compare the ticks

if t1.Ticks < t2.Ticks then
Thanks Cor! This is what I needed.
(the bracket is not needed in VBNet)
I know, but sometimes I use C#, and in my mind brackets make it more
readable - so is there any reasons as an example why I should't use
brackets with VB.NET where brackets are not needed?
 
Mika,
I know, but sometimes I use C#, and in my mind brackets make it more
readable - so is there any reasons as an example why I should't use
brackets with VB.NET where brackets are not needed?

I find it just not looking good. For me it tells that there is something
extra with the evaluated expression. While that is not in your case.
However, probably just a matter of preference. Therefore do it as you wish.

Cor
 
I need to compare two DateTime variables named as t1 and t2 using VB.NET
2003. If t1 is any earlier time as t2, only then program should do
something like...

If (t1 < t2) Then
'DoSomethingHere...
End If

But I don't figue out how comparing DateTimes is working.

I tried to compare these variables with same time in Immediate-window...

Are you certain they were the same (milliseconds and ticks, not just the
formatted string)?
I'm using > and < operators directly on dates all the time.

Try this code:

Dim d1, d2 As Date
Dim dt1, dt2 As DateTime
d1 = Now
d2 = d1
dt1 = d1
dt2 = d1
Debug.WriteLine((d1 < d2) & ", " & (d1 = d2) & ", " & (d1 > d2))
Debug.WriteLine((dt1 < dt2) & ", " & (dt1 = dt2) & ", " & (dt1 > dt2))

d2 = d2.AddMilliseconds(1)
dt2 = d2
Debug.WriteLine((d1 < d2) & ", " & (d1 = d2) & ", " & (d1 > d2))
Debug.WriteLine((dt1 < dt2) & ", " & (dt1 = dt2) & ", " & (dt1 > dt2))

Result:

False, True, False
False, True, False
True, False, False
True, False, False
 
Back
Top