简体   繁体   中英

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).

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...). I want this value returned as a floored integer (so, if 3.4 timespans have passed, it should return 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; 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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