C#在一个时间跨度内的时间跨度计数

ibi*_*iza 3 c# timespan

我想知道在C#中做到这一点的方法

假设我有2个时间跨度:TS1为3h,TS2为12h.

计算TS1在TS2内可以进行多少次的最快方法是什么?在这种情况下,输出将是4.

如果TS1是8天而TS2是32天,它也将返回4.

Mat*_*hen 8

整数划分?

(int) TS1.TotalMilliseconds/(int) TS2.TotalMilliseconds;
Run Code Online (Sandbox Code Playgroud)


Han*_*ant 8

是的,使用整数除法.但魔鬼在细节中,一定要使用时间跨度中不可或缺的属性,以避免溢出和四舍五入问题:

 int periods = (int)(TS1.Ticks / TS2.Ticks);
Run Code Online (Sandbox Code Playgroud)