简体   繁体   English

计算两个日期之间的时间跨度

[英]Calculate how many timespans are between two dates

let's say I have a timespan variable that is a timespan that can be anything, from seconds, to hours, days... (I need to be able to set this in different ways). 假设我有一个timepan变量,它是一个可以是任何东西的时间跨度,从几秒到几小时,几天......(我需要能够以不同的方式设置它)。

I want to calculate how many timespans occurred between two given DateTime (like, say I have a timespan of 1 hour, how many hours passed between those two datetimes. But it can also be 1 hour and a half or 3 minutes...). 我想计算两个给定DateTime之间出现的时间跨度(比如说,我有1小时的时间跨度,在这两个日期时间之间经过了多少小时。但它也可以是1小时半或3分钟......) 。 I want this value returned as a floored integer (so, if 3.4 timespans have passed, it should return 3). 我希望这个值作为一个被覆盖的整数返回(因此,如果已经过了3.4个遍,它应该返回3)。

What's the best way to do it? 最好的方法是什么? I'm not familiar with datetime and I'm a little bit wrapping my head around this :) 我对日期时间并不熟悉,而且我有点围绕着这个:)

Cheers! 干杯!

TimeSpan comes down to the long Ticks property; TimeSpan归结为long Ticks属性; you can simply perform integer division. 你可以简单地执行整数除法。

int x = 10 / 3; // equals 3

TimeSpan period = TimeSpan.FromSeconds(5);
TimeSpan difference = laterDateTime - earlierDateTime;

var periodFitsThisManyTimes = difference.Ticks / period.Ticks;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM