3

Possible Duplicate:
Difference in months

Hi all:

how can We calculate the months difference between two dates using LINQ ? I can find days difference using:

(p.Account.StateChangeDate.Date - DateTime.Now.Date).Days < 4

but there is no option for months.

Please suggest.

Community
  • 1
  • 1
DotnetSparrow
  • 27,428
  • 62
  • 183
  • 316
  • This has nothing to do with LINQ, it is simply about calculating a date interval in months (as per the dupe). – Steve Apr 01 '11 at 16:19
  • In your case, how long is a month, 28, 29, 30 or 31 days? OR are you expecting a whole number of months and a number of days, in which case what happens when going from the 15th of Feb to the 17th April, is it 1 month and 30 days? or 2 months and 2 days? – Adam Straughan Apr 01 '11 at 16:20
  • I need generic function to calculate the difference of months between two dats and use it in LINQ query – DotnetSparrow Apr 01 '11 at 16:42
  • Check this out for the 100% accurate definition (and code to calculate) .Months - it's not in LINQ but you can convert to it easy. The .NET frameworks ignorance of this issue is fixable with this post: http://stackoverflow.com/questions/1916358/a-real-timespan-object-with-years-months – Erx_VB.NExT.Coder Feb 15 '12 at 05:32

2 Answers2

2

Try calculating the difference in months between two dates


Pick the algorithm you want to use from that question.

Then, if you are using Linq2Sql, then almost all of those will get mapped back to the database as DATEPART type operations (I think).

Alternatively you could do the calc in SQL using a function like in http://www.sqlmag.com/article/sql-server/calculating-month-difference.aspx - and could then expose that to Linq2Sql as a function

Community
  • 1
  • 1
Stuart
  • 66,722
  • 7
  • 114
  • 165
0

This should calculate the months for you but it is irregular because some months have 30 days and february, for example, can have 28 or 29.

int months = MaxDate.Subtract(MinDate).Days / 30;
Hallaghan
  • 1,910
  • 6
  • 32
  • 47