how to perform division in timespan [duplicate]
Asked Answered
D

3

23

I have a value in TimeSpan, let's say: tsp1 = 2 hour 5 minutes. I have another TimeSpan variable which contains a value like: tsp2 = 0 hours 2 minutes

Please tell me how I can divide tsp1 by tsp2 so that I can get the exact number of times tsp2 divides into tsp1 and what the remainder is.

I am using Visual Studio 2008.

Thanks.

Disassembly answered 29/11, 2010 at 10:1 Comment(0)
S
43

The simplest approach is probably just to take their lengths in ticks, and divide those. For example:

long ticks1 = tsp1.Ticks;
long ticks2 = tsp2.Ticks;

long remainder;
long count = Math.DivRem(ticks1, ticks2, out remainder);

TimeSpan remainderSpan = TimeSpan.FromTicks(remainder);

Console.WriteLine("tsp1/tsp2 = {0}, remainder {1}", count, remainderSpan);
Sonorous answered 29/11, 2010 at 10:4 Comment(0)
M
8

a div b:

double adivb = (double)a.Ticks/b.Ticks;

edited:

i found another post on th same topic

How can I achieve a modulus operation with System.TimeSpan values, without looping?

Moribund answered 29/11, 2010 at 10:5 Comment(0)
G
2

An int will hold enough seconds for ~64 years, so as long as you stay well below that:

int count = (int) (tsp1.t.TotalSeconds / tsp2.t.TotalSeconds);
double remainder = tsp1.t.TotalSeconds - (count * tsp2.t.TotalSeconds);

And maybe convert the remainder to int as well.

Gotama answered 29/11, 2010 at 10:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.