Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I truncate milliseconds off "Ticks" without converting to datetime?

Tags:

c#

datetime

I have two times in Ticks like so:

//2016-01-22​T17:34:52.648Z
var tick1 = 635890808926480754;

//2016-01-22​T17: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?

like image 774
User1 Avatar asked Jan 26 '16 16:01

User1


1 Answers

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.

like image 104
Dmitry Avatar answered Sep 27 '22 20:09

Dmitry