AomSet
AomSet

Reputation: 383

Calculate difference between two dates returns a negative number

I am trying to calculate how many days there are between different dates. Like the topic says, I'm getting a negative value. I guess I could just take the absolute value, but the fact that it returns a negative value, makes me doubt if the calculations are correct. Below is my code:

DateTime previousDay = new DateTime(1998, 6, 31, new GregorianCalender());
DateTime nextDay = new DateTime(1998, 6, 3, new GregorianCalender());

TimeSpan differenceInDays = (nextDay - previousDay); 
double xAxisValue = differenceInDays.TotalDays;

Ofcourse 3-31 gives -28, but since we want it to show days between, it makes no sense that it doesn't return a positive value. Am I doing something wrong?

I also tried this approach:

(a - b).TotalDays

where a and b are of type Datime

Upvotes: 2

Views: 11065

Answers (4)

Maciej Jureczko
Maciej Jureczko

Reputation: 1598

This is expected behavior.

You should use the TimeSpan.Duration() method.

It returns a new TimeSpan object whose value is the absolute value of the current TimeSpan object.

http://msdn.microsoft.com/en-us/library/system.timespan.duration.aspx

Upvotes: 10

Ehsan
Ehsan

Reputation: 32681

Ofcourse 3-31 gives -28, but since we want it to show days between, it makes no sense that it doesn't return a positive value. Am I doing something wrong?

I think that you don't know which date is greater before hand.And your naming is just confusing.

You can first check which date is greater and then subtract the Lesser from the greater

TimeSpan differenceInDays;
double xAxisValue;
if(nextDay > previousDay )
{
    differenceInDays = (nextDay - previousDay); 
}
else
{
    differenceInDays = (previousDay - nextDay); 
}
xAxisValue = differenceInDays.TotalDays;

Upvotes: 2

Amir Keshavarz
Amir Keshavarz

Reputation: 3108

I think this is because of there is no '1998-06-31' date in the calendar.

Upvotes: 6

Jon Skeet
Jon Skeet

Reputation: 1500695

I guess I could just take the absolute value, but the fact that it returns a negative value, makes me doubt if the calculations are correct.

Why? nextDay is earlier than previousDay, so of course subtracting previousDay will give a negative result.

You're effectively asking "How many days do I need to add to previousDay in order to get to nextDay? The answer is -28.

What does concern me is the names here - I'd expect a nextDay value to always be later than a previousDay value - so either the way you're finding those values is incorrect, or you need to change the names to make the meaning clearer. Presumably they're not "next" and "previous" in respect to the same context.

Upvotes: 13

Related Questions