C# 两个日期之间的天差
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2330302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Days difference between two dates
提问by Ben Orozco
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
采纳答案by Josh
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).
可以减去 DateTime 以获得 TimeSpan。TimeSpan 有一个 TotalDays,它是天数(也包括小数天)。
int DaysBetween(DateTime d1, DateTime d2) {
TimeSpan span = d2.Subtract(d1);
return (int)span.TotalDays;
}
NOTETime 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...
注意时间跨度是有符号的。如果 d1=1/9/11 且 d2=1/11/11,则 d1.subtract(d2)=-2 天的时间跨度。因此,如果您想使用时间跨度来确定日期之间是否在 X 天内,则需要取总天数的绝对值...
Math.Abs(span.TotalDays)
回答by casperOne
You can use the subtraction operatoron the two instances of DateTime
(or DateTimeOffset
, as it has the same subtraction operator, and it is the recommended structure to use for date values in .NET) to get a TimeSpan
instance.
您可以在(or的两个实例上使用减法运算符,因为它具有相同的减法运算符,并且它是.NET 中用于日期值的推荐结构) 来获取实例。DateTime
DateTimeOffset
TimeSpan
Once you have that, you can call the Days
propertyto get the number of whole days that the TimeSpan
represents.
一旦有了它,您就可以调用该Days
属性以获取该属性所TimeSpan
代表的天数。
If you want the number of whole and fractional days, then look at the TotalDays
property.
如果您想要整数天数和小数天数,请查看TotalDays
属性。
In your specific case, it seems that you want to add 1 to whatever value the Days
property returns, as your custom calculation indicates that for two DateTime
instances that represent the same value, the result is 1.
在您的特定情况下,您似乎想为Days
属性返回的任何值加 1 ,因为您的自定义计算表明对于DateTime
表示相同值的两个实例,结果为 1。
回答by Mike Marshall
DateTime dtOne;
DateTime dtTwo;
// to get the total days in between
int answer = (dtTwo - dtOne).TotalDays