天两个日期之间的差额 [英] Days difference between two dates
问题描述
我一直想很多方法来计算两个日期之间的天数轮,我的意思是,计算整个天。什么,我需要一个例子:
I've been trying many ways to calculate the round number of days between two dates, I mean, counting the whole days. An example of what I need:
START DATE END DATE Day Count
24/02/2010 16:26 24/02/2010 16:26 1
20/02/2010 18:16 24/02/2010 16:26 5
31/12/2009 20:00 24/02/2010 16:26 56
15/07/2009 20:59 24/02/2010 16:26 225
推荐答案
日期时间的可减去得到一个时间跨度。的时间跨度具有TotalDays是天数(包括小数天以及)。
DateTime's can be subtracted to get a TimeSpan. The TimeSpan has a TotalDays which is the number of days (includes fractional days as well).
int DaysBetween(DateTime d1, DateTime d2) {
TimeSpan span = d2.Subtract(d1);
return (int)span.TotalDays;
}
注意的时间跨度签署。如果D1 = 1/9/11和D2 = 1/11/11,然后d1.subtract(D2)= -2天的时间跨度。所以,如果你想使用的时间跨度,以找出是否日期是在彼此的X天,你需要采取总天数的绝对值...
NOTE Time spans are signed. If d1=1/9/11 and d2=1/11/11, then d1.subtract(d2)=timespan of -2 days. So if you want to use a time span to find out if dates are within X days of each other, you need to take the absolute value of the total days...
Math.Abs(span.TotalDays)
这篇关于天两个日期之间的差额的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!