41

I have two calendars and each return a DateTime from calendar.SelectedDate.

How do I go about subtracting the two selected dates from each other, giving me the amount of days between the two selections?

There is a calendar.Subtract() but it needs a TimeSpan instead of DateTime.

Ufuk Hacıoğulları
  • 37,978
  • 12
  • 114
  • 156
sd_dracula
  • 3,796
  • 28
  • 87
  • 158

3 Answers3

56

You can use someDateTime.Subtract(otherDateTime), this returns a TimeSpan which has a TotalDays property.

C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72
  • You can also pass `Subtract()` a `TimeSpan` and it will return a `DateTime`. http://msdn.microsoft.com/en-us/library/ae6246z1%28v=vs.110%29.aspx – northben Jul 16 '14 at 04:02
36

Just use:

TimeSpan difference = end - start;
double days = difference.TotalDays;

Note that if you want to treat them as dates you should probably use

TimeSpan difference = end.Date - start.Date;
int days = (int) difference.TotalDays;

That way you won't get different results depending on the times.

(You can use the Subtract method instead of the - operator if you want, but personally I find it clearer to use the operator.)

Bhushan Firake
  • 9,338
  • 5
  • 44
  • 79
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

Think about it.
How do you express a difference betwen two dates? With another date?
That's why you need the TimeSpan

DateTime dtToday = new System.DateTime(2012, 6, 2, 0, 0, 0);
DateTime dtMonthBefore = new System.DateTime(2012, 5, 2, 0, 0, 0);
TimeSpan diffResult = dtToday.Subtract(dtMonthBefore);
Console.WriteLine(diffResult.TotalDays);
Steve
  • 213,761
  • 22
  • 232
  • 286
  • Actually there are various issues with using TimeSpan to represent the difference between two dates, but in *this* case it's okay :) – Jon Skeet Jun 03 '12 at 16:04
  • Thanks for all the input. Actually I only need the day and I did not see that the Subtract method can also take a DateTime parameter meaning all I need is this: untilCalendar.SelectedDate.Subtract(fromCalendar.SelectedDate).Days – sd_dracula Jun 03 '12 at 16:07
  • @sd_dracula: Do you definitely prefer using the `Subtract` method rather than the operator? – Jon Skeet Jun 03 '12 at 16:54