Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi!!,
For one of my project i'm using DateDiff function in a timer as mentioned below:-

NoOfValues = DateDiff(DateInterval.Second, StartTime, EndTime)

the values of StartTime, EndTime & NoOfValues for a cycle of execution are as mentioned below

CSS
Start Time= 11/18/2013 4:28:46 PM   End Time= 11/18/2013 4:29:37 PM
NoOfValues= 51

Start Time= 11/18/2013 4:29:38 PM   End Time= 11/18/2013 4:29:49 PM
NoOfValues= 10

Start Time= 11/18/2013 4:29:50 PM   End Time= 11/18/2013 4:30:00 PM
NoOfValues= 10


I'm not able to understand how the difference of
CSS
[11/18/2013 4:29:38 PM & 11/18/2013 4:29:49 PM] =10 


Plz guide me whether i've used DateDiff function correctly.
Posted
Comments
Mike Meinz 18-Nov-13 8:56am    
Rounding errors.

DateTime data type values are stored as "Ticks". A tick is one ten-millionth of a second. There are 10,000 ticks in a millisecond. Occasionally, you will see results like you have seen.

It is a best practice to use >= or <= comparisons rather than equality comparisons when comparing computed values because of the potential for rounding errors.

See Rounding Errors Tutorial.

1 solution

You could use a TimeSpan to handle calculations on your DateTime values:
VB
Dim myDate1 As DateTime = new DateTime(2013, 11, 18, 4, 29, 38);
Dim myDate2 As DateTime = new DateTime(2013, 11, 18, 4, 29, 49);
TimeSpan ts = myDate2 - myDate1;
long elapsedInMilliseconds = ts.Elapsed;
float valueInSeconds = (float)elapsedInMilliseconds / 1000f;
int value = Math.Floor(valueInSeconds);
 
Share this answer
 
v2
Comments
DDR-4 18-Nov-13 10:12am    
Thanks Mike Meinz & phil.o for your reply,
But my query is about Datediff function,which is supposed to give difference between two dates whereas, in case of my code(refer the question) i'm not getting correct date difference in seconds.
phil.o 18-Nov-13 10:26am    
It surely is because of a rounding error.
You could test your piece of code and mine, point the differrences between both of them, and make your choice.
Good luck.
DDR-4 19-Nov-13 0:14am    
as you said rounding error is there, for example:-
If Start Time= 11/19/2013 10:40:14 AM End Time= 11/19/2013 10:41:05 AM
the difference should be 51 but i'm getting 50
if i perform
Dim TmStmp As TimeSpan = EndTime - StartTime
then value of TmStmp is 00:00:50.0140580
&
TmStmp._ticks= 500140580
TotalMilliseconds=50014.05800..
With this information how can we apply the correction.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900