C#两个日期之间的天数问题 [英] C# Number of days between two dates problem
问题描述
下面的代码有一个小问题,无论天数相隔多远, days变量始终看起来为0。
I have a small problem with the code below, the 'days' variable always seems to be 0 no matter how far apart the days are.
有什么明显的错误吗?
Can you see anything obviously wrong?
System.TimeSpan span = dates[0] - dates[1]; // e.g. 12/04/2010 11:44:08 and 18/05/2010 11:52:19
int days = (int)span.TotalDays;
if (days > 10) //days always seems to be 0
{
throw new Exception("Over 10 days");
}
谢谢
推荐答案
当您从较早的日期中减去较晚的日期时,根据您的评论,TotalDays将为负数。在您的示例中为-36。
As you are subtracting the later date from the earlier date, according to your comments, TotalDays will be negative. In your example, -36.
因此,(天数> 10)
的比较将失败。您应该使用
Therefore a comparison of (days > 10)
will fail. You should use
int days = Math.Abs((int)span.TotalDays);
假设您未将date [0]设置为等于date [1],则没有理由为什么TotalDays对于您的注释中的样本日期将返回零。
Assuming you haven't set date[0] equal to date[1], there is no reason why TotalDays will be returning zero for the sample dates you have in your comments.
这篇关于C#两个日期之间的天数问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!