Jamie
Jamie

Reputation: 2565

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.

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

Upvotes: 1

Views: 7348

Answers (5)

code4life
code4life

Reputation: 15794

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

Upvotes: 0

Petar Minchev
Petar Minchev

Reputation: 47363

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.

Upvotes: 4

Simon
Simon

Reputation: 9365

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.

Upvotes: 1

Neil Moss
Neil Moss

Reputation: 6818

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.

Upvotes: 6

Tesserex
Tesserex

Reputation: 17314

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?

Upvotes: 0

Related Questions