Comparing and adding to dates?

Adagio

Well-known member
Joined
Dec 12, 2005
Messages
162
Programming Experience
Beginner
I have a sub with this:

public sub DoSomething()
Dim dte As Date = someDate
dte.AddSeconds(5)

If dte < Date.Now Then
' doSomeCode
End If
end sub

someDate is set when some other sub is called ( someDate = date.now )
What I want to happen is that the code inside the if tag in DoSomething() should only be used when at least 5 seconds has passed since the other sub was called

Using the above code gives me two problems. First the AddSeconds(5) sub doesn't add 5 seconds to it's value. After calling AddSeconds the dte.Seconds is the same as someDate.Seconds... why? I would have guessed that calling AddSeconds(5) would add 5 seconds to it's value... :confused:

Then there's the problem with the IF date < date part. The first time DoSomething() is called is when dte is the exact same as date.now... but why does it still execute the code inside the if tag if they are the same?
 
Solved!

Try this:

Dim myDate As Date = Date.Now
Dim myDate2 As Date = Date.Now
myDate2.AddSeconds(5)
MsgBox(
"DATE1: " & myDate.ToLongTimeString & vbCrLf & "DATE2: " & myDate2.ToLongTimeString)


You will see that the times shown are exactly the same!

But if you replace the third row with

myDate2 = myDate2.AddSeconds(5)

So the code will be

Dim myDate As Date = Date.Now
Dim myDate2 As Date = Date.Now
myDate2 = myDate2.AddSeconds(5)
MsgBox(
"DATE1: " & myDate.ToLongTimeString & vbCrLf & "DATE2: " & myDate2.ToLongTimeString)

It will show the 5 seconds!


In your code replace
dte.AddSeconds(5)
with:

dte = dte.AddSeconds(5)

 
After calling AddSeconds the dte.Seconds is the same as someDate.Seconds... why?

Same reason that

Dim s as String = "Hello world"
s.Substring(0, 5)

doesnt reduce the string to just "hello".

For all things that are immutable, any operation that makes as if to change the immutable, actually returns a new immutable with the changes applied.


The first time DoSomething() is called is when dte is the exact same as date.now... but why does it still execute the code inside the if tag if they are the same?

Becuase the time when you called Date.Now first, was THEN.. it is NOW something different, even a few milliseconds..

Dim d as DateTime = DateTime.Now 'exactly midnight

'some code
If d < DateTime.Now Then.. 'now = midnight and 3 milliseconds. d is in the past, by 3 milliseconds!
 
Back
Top