tags:

views:

112

answers:

4

I would like to know a way to do this in C#

Let's say I have 2 timespans : TS1 is 3h and TS2 is 12h.

What is the fastest way to calculate how many times TS1 can go within TS2? In that case, the output would be 4.

if TS1 is 8 days and TS2 is 32 days, it would return 4 as well.

+7  A: 

Integer division?

(int) TS1.TotalMilliseconds/(int) TS2.TotalMilliseconds;
Matthew Flaschen
Yes, this is an example of getting it subtly wrong.
Hans Passant
@Hans, you can make a case that using `Ticks` is better, and I up-voted you. But there is no sign the OP cares about sub-millisecond precision. In fact, the smallest unit he uses is an hour.
Matthew Flaschen
Well, I agree and +1 one for pointing out integer division. You could have used TimeSpan.TotalHours following that logic though, I only posted to point out the 'fall into the pit of success' angle.
Hans Passant
have both +1 and thanks for your answers :)
ibiza
+1  A: 

int count = (int)(ts2.TotalSeconds / ts1.TotalSeconds);

BrokenGlass
ah always gets me...fixed
BrokenGlass
+2  A: 

You can divide the TotalMilliseconds from one by the other. That is:

double times = TS2.TotalMilliseconds / TS1.TotalMilliseconds
Jim Mischel
+5  A: 

Yes, use integer division. But the devil is in the details, be sure to use an integral property of a TimeSpan to avoid overflow and round-off problems:

 int periods = (int)(TS1.Ticks / TS2.Ticks);
Hans Passant
+1 for obvious reasons
Fredrik Mörk
+1 for using ticks.
kirk.burleson
well thanks ;>_<
ibiza