开发者

C# Number of days between two dates problem

开发者 https://www.devze.com 2022-12-30 11:44 出处:网络
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.

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 obvious开发者_StackOverflow社区ly 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. In your example, -36.

Therefore a comparison of (days > 10) will fail. 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.


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.


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. So it should perfectly work! One question: Did you use DateTime[] for the dates-array?

BTW: days > 10 does not check if days is zero.


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

精彩评论

暂无评论...
验证码 换一张
取 消