Ciaran Gallagher - 9 months ago 62

C# Question

In my system, I am storing a duration in Ticks, which is being passed to my client mobile application, and from there I want to convert ticks into a human readable form. In my case, days, hours and minutes.

My client mobile application is coded using Javascript, and so this is what I'm using to convert the duration to days/hours/minutes.

Answer

In C# .NET, a single tick represents one hundred nanoseconds, or one ten-millionth of a second. [Source].

Therefore, in order to calculate the number of days from the number of ticks (rounded to nearest whole numbers), I first calculate the number of seconds by multiplying by ten million, and then multiplying that by the number of seconds in a day (60 seconds in minute, 60 minutes in hour, 24 hours in day). I use the modulus operator (%) to get the remainder values that make up the duration of hours and minutes.

```
var time = 3669905128; // Time value in ticks
var days = Math.floor(time/(24*60*60*10000000)); // Math.floor() rounds a number downwards to the nearest whole integer, which in this case is the value representing the day
var hours = Math.round((time/(60*60*10000000)) % 24); // Math.round() rounds the number up or down
var mins = Math.round((time/(60*10000000)) % 60);
console.log('days: ' + days);
console.log('hours: ' + hours);
console.log('mins: ' + mins);
```

So, in the above example, the amount of ticks is equivalent to 6 minutes (rounded up).

And to take another example, with 2,193,385,800,000,000 ticks, we get 2538 days, 15 hours and 23 minutes.

Source (Stackoverflow)