blah blah blah is here! blah blah » Close

up0down
link

I'm trying to match a certain DateTime value with the current system DateTime. I have a timer and a label on a form. Timer interval is set to 1000. When the form loads, the timer starts ticking. As soon as the current DateTime matches the value of the variable, it shows a message in the label.

When I'm writing the following code, the values don't match even if the current system DateTime is equal to the variable. Label1 isn't showing 'Times Matched':

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim dtmNow As DateTime
dim dtmVar as DateTime=#04/28/2010 03:25:00 AM#

dtmNow = Now
If dtmVar = dtmNow Then Label1.Text = "Times Matched"
End Sub

But when I'm writing the same code by parsing 'Now' into DateTime it's working fine.

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim dtmNow As DateTime
dim dtmVar as DateTime=#04/28/2010 03:25:00 AM#

dtmNow = DateTime.Parse(Now.ToString)
If dtmVar = dtmNow Then Label1.Text = "Times Matched"
End Sub

Why is it so? The default format of 'Now' is the same as I have stored in dtmVar variable. So there's no question of format mismatch. Does that mean 'Now' is not actually a DateTime property?
Provided, my O.S. is Windows Vista Ultimate and all date/time settings are set to default.
Regards.

last answered one year ago

1 answers

up0down
link

I think the problem here is that DateTime values are measured in ticks where one tick equals one hundred nanonseconds.

However, when you convert a DateTime value to a string (using the default ToString() format) the value is displayed to the nearer second. Similarly, when you use a DateTime literal, this will also be an exact multiple of a second.

So, in your first version of Timer1_Tick, 'dtmNow' contains the value of 'Now' in ticks at the instant when the assignment is made. This is very unlikely to be equal to an exact multiple of seconds (remembering you're assigning a DateTime literal to 'dtmVar') and so the times are never matched.

However, in your second version of Timer1_Tick, 'Now' is first parsed to a string and then parsed back to a DateTime and so will represent an exact multiple of a second. Consequently, when you compare it with a DateTime literal, it is possible for the times to match.

So, I think the answer here is to work with the string representation of DateTime values rather than the values themselves when matching them.

Feedback