简体   繁体   English

C#两个日期之间的天数问题

[英]C# Number of days between two dates problem

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. 我的下面的代码有一个小问题,无论天数相隔多远,“ days”变量似乎总是为0。

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");
        }

Thanks 谢谢

As you are subtracting the later date from the earlier date, according to your comments, TotalDays will be negative. 当您从较早的日期中减去较晚的日期时,根据您的评论,TotalDays将为负数。 In your example, -36. 在您的示例中,为-36。

Therefore a comparison of (days > 10) will fail. 因此, (days > 10)的比较将失败。 You should use 你应该用

int days = Math.Abs((int)span.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. 假设您未将date [0]设置为等于date [1],则没有理由为注释中的示例日期TotalDays返回零。

The total days should be negative but in any case not zero, cause you substract the earlier date from the later date. 总天数应为负数,但无论如何不能为零,因为您要从较晚的日期中减去较早的日期。 It seems dates[0] and dates[1] are not containing what you think. 看来dates[0]dates[1]不包含您的想法。

I just tested this: 我刚刚测试了这个:

DateTime date1 = new DateTime(2010, 12, 31);
DateTime date2 = new DateTime(2010, 1, 1);

TimeSpan timeSpan = date2 - date1;
Console.WriteLine(timeSpan.TotalDays);

This program produces the output: -364 . 该程序产生输出: -364 So it should perfectly work! 所以它应该完美地工作! One question: Did you use DateTime[] for the dates -array? 一个问题:您是否将DateTime[]用于dates数组?

BTW: days > 10 does not check if days is zero. 顺便说一句: days > 10不会检查days是否为零。

If we assume your code looks exactly like that, and the dates array is correctly populated, then there is nothing wrong here that would cause days to be exactly zero. 如果我们假设您的代码看起来完全像这样,并且正确地填充了dates数组,那么这里没有什么错误会导致天数完全为零。 Maybe check that your dates array has the correct values in it? 也许检查一下您的日期数组中是否有正确的值? Barring that, post more code? 除此以外,发布更多代码?

Either do this: 要么这样做:

System.TimeSpan span = dates[0] - dates[1]; 
int days = Math.Abs((int)span.TotalDays);

if (days > 10)
{
    throw new Exception("Over 10 days");
}

Or this: 或这个:

System.TimeSpan span = dates[1] - dates[0]; 
int days = (int)span.TotalDays;

if (days > 10)
{
    throw new Exception("Over 10 days");
}

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

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