tags:

views:

402

answers:

5

Hi all,

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

+4  A: 

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.

Petar Minchev
TimeSpans can be negative, so it wouldn't be exactly 0.
Tesserex
@Tesserex, thanks for the info.
Petar Minchev
-1: This is simply incorrect
Simon
@Simon I understood that, I will update my answer.
Petar Minchev
A: 

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?

Tesserex
+5  A: 

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.

Neil Moss
A: 

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.

Simon
A: 

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