Reputation: 18799
I have two times in Ticks
like so:
//2016-01-22T17:34:52.648Z
var tick1 = 635890808926480754;
//2016-01-22T17:34:52.000Z
var tick2 = 635890808920000000;
Now as you can see comparing these two numbers tick1 == tick2 returns false
although the dates are the same (apart from milliseconds).
I would like to truncate the milliseconds off these numbers without converting it to a datetime (because this would reduce efficiency)
I have looked at Math.Round which says:
Rounds a value to the nearest integer or to the specified number of fractional digits.
and also Math.Truncate neither of which I think do what I need.
Looking at Datetime.Ticks it says:
A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond, or 10 million ticks in a second.
Therefore I need to round the number down to the nearest ten million.
Is this possible?
Upvotes: 6
Views: 1928
Reputation: 14059
You could use integer division:
if (tick1 / TimeSpan.TicksPerSecond == tick2 / TimeSpan.TicksPerSecond)
This works because if you divide a long
/int
by a long
/int
the result is also a long
/int
therefore truncating the decimal portion.
Upvotes: 11
Reputation: 29441
You can use this:
if(Math.Abs(tick1 - tick2) < TimeSpan.TicksPerSecond)
Which avoid doing divisions.
You may adjust the precision you need with any of the following:
TimeSpan.TicksPerDay
TimeSpan.TicksPerHour
TimeSpan.TicksPerMinute
TimeSpan.TicksPerSecond
TimeSpan.TicksPerMillisecond
Upvotes: 7
Reputation: 2083
Divide it by 1000 like this:
Long Seconds = 635890808926480754/1000
//Seconds = 635890808926480
Upvotes: -1